原帖地址 http://blog.csdn.net/cherry609195946/article/details/19609485
一. 基本概念
1. OC中没有命名空间机制,也没有包的概念,为了区分不同的类,在类名前加前缀
2. OC中的关键字都以@开头,用于区分C和C++的关键字,字符串也以@开头,比如:
- @interface Student : NSObject
- NSLog(@"Hello World!");
二. 面向对象
1. @interface --------> 等于java中的class
2. 类名后的冒号:---------> 等于java中的extends
3. 函数前面的减号- ---------> 表示对象方法
函数前面的加号+ ---------> 表示类方法,等于java的static方法
4. 函数的返回类型和参数的类型必须用括号,形参用冒号:表示
以bean类的头文件示例:
- @interface Student : NSObject{
- int age;
- int height;
- }
-
- - (int)age;
- - (void)setAge:(int)newAge;
-
- - (void)setAge:(int)newAge andHeight:(int)newHeight;
- @end
对应的m文件为:
- #import "Student.h"
- @implementation Student
-
- - (int)age{
- return age;
- }
- - (void)setAge:(int)newAge{
- age = newAge;
- }
- - (void)setAge:(int)newAge andHeight:(int)newHeight{
- age = newAge;
- height = newHeight;
- }
- @end
5. 对象的创建和方法调用:
-
-
-
-
- Student *stu = [[Student alloc] init];
-
- [stu setAge:100];
- [stu setAge:100 andHeight:50];
-
- NSLog(@"age is %i",[stu age]);
- [stu release];
6. 对象的构造方法
- @interface Student{
- int _age;
- int _no;
- }
- - (void)setAge:(int)age;
- - (int)age;
- - (void)setNo:(int)no;
- - (int)no;
-
- - (id)initWithAge:(int)age andNo:(int)no;
- @end
对应的m文件:
- #include "Student.h"
- @implementation Student
-
- - (int)age{
- return _age;
- }
- - (void)setAge:(int)age{
- _age = age;
- }
-
-
- - (id)initWithAge:(int)age andNo:(int)no{
-
-
-
-
- if(self=[super init]){
- _age = age;
- _no = no;
- }
- return self;
- }
- @end
7. @property简化set和get
在头文件中这样声明:
在m文件中这样实现:
8. 使用@class 提高编译效率,由于在h文件中,使用include的话,是将其内容全部拷贝过来,会影响编译效率,而且对应的h文件只有有任何改动,又要重新编译,为了解决这个问题,在h文件中,如果引用了另外一个对象,则使用@class Object; 代替include语法,用于告诉编译器该对象是存在的
- @class Book;
- @interface Student : NSObject
- @property Book *book;
- @end
但是在对应的m文件中,则必须要include入Book.h了.
原帖地址 http://blog.csdn.net/cherry609195946/article/details/19609485