声明
类的声明,又称类的前向声明,即forward declaration,告诉编译器class类型,但当前并不知道class具体细节,是不完全类型
- 类的声明只能用于指针类型,因为指针类型字长固定,编译器知道分配多少内存空间,如何操作指针类型
- 类的声明不能用于对象(instance object&class object),因为对于instance object,编译器需要知道class object内容,对于class object,编译器需要知道meta-class object内容
@class FBAnimal;
void incomplete_class()
{
FBAnimal *animal;
//animal = [[FBAnimal alloc] init];
}
定义
@interface FBAnimal : NSObject
{
@public
int _rice;
int _meat;
}
- (void)feedRice:(int)rice;
- (void)feedRice:(int)rice andMeat:(int)meat;
+ (void)setMain:(int)main;
+ (void)setMain:(int)main andSub:(int)sub;
@end
注:类所有方法都是运行期bind,因此类必须提供实现,否则link error,因为编译器编译期无法确定方法成员(instance method和class method)是否被访问
实现
@implementation FBAnimal
- (void)feedRice:(int)rice
{
NSLog(@"feedRice:");
}
- (void)feedRice:(int)rice andMeat:(int)meat
{
NSLog(@"feedRice:andMeat:");
}
+ (void)setMain:(int)main
{
NSLog(@"setMain:");
}
+ (void)setMain:(int)main andSub:(int)sub
{
NSLog(@"setMain:andSub");
}
@end
注:类所有方法都是运行期bind,编译器编译期无法确定方法成员(instance method和class method)是否被访问,为避免运行期crash,类所有方法必须提供实现,否则编译warning
总结
- @class classname——类的声明,@interface classname——类的定义,@implement classname——类的实现
- 类的定义和实现编译成为class object&meta-class object内容:数据成员定义编译成为class object内容,instance method实现编译成为class object内容,class method实现编译成为meta-class object内容
self&成员访问
self类似于c++的this,表示当前instance object,instance object访问数据成员和instance method,class object访问class method,因此:
- self只能出现在instance method中,只能访问数据成员和instance method,不能访问class method,instance method中存在instance object,无class object
- self不能出现在class method中,class method中只能访问class method,不能访问数据成员和instance method,class method中存在class object,无instance object
- (void)use_animal
{
FBAnimal *animal = [[FBAnimal alloc] init];
animal->_rice = 5;
animal->_meat = 8;
[animal feedRice:15];
[animal feedRice:15 andMeat:18];
[FBAnimal setMain:25];
[FBAnimal setMain:25 andSub:28];
}
output:
feedRice:
feedRice:andMeat:
setMain:
setMain:andSub