一、 Id
1. 简介
万能指针,能指向任何OC对象相当于NSObject*
id类型的定义
typedef struct objc object{
Class isa;
} *id;2. 使用
//注意:id后面不要加上*
Id p = [Person new];3. 局限性
调用一个不存在的方法,编译器会自动报错
二、 构造方法(用来初始化对象的方法,是个对象方法,-开头)
1. 对象的创建原理
New的拆分两部曲
分配内存(+alloc)
初始化(-init)
Person *p = [person alloc];
Person *p1 = [p init];
2. Init方法的重写(想在对象创建完毕后,成员变量马上就有一些默认的值)
a. 一定要调用会super的init方法:初始化父类中声明的一些成员变量和其他属性
b. 如果对象初始化成功,才有必要进行接下来的初始化
c. 返回一个已经初始化完毕的对象
- (id)init
{
Self =[super init];
If(self!=nil)
{
_age= 10;
}
return self;
}等价于(建议写成这种样式)
-(id)init
{
If(self = [super init])
{
_age= 10;
}
return self;
}3. 自定义构造方法
自定义构造方法的规范
a. 一定是对象方法,一定以– 开头
b. 返回值一般是id类型
c. 方法名一般以initWith开头
- (void)initWithAge:(int)age
{
if(self = [super init])
{
_age = age;
}
return selfl;
}- (id)initWithName:(NSString *)name andAge:(int)age andNo:(int)no
{
if(self = [super initWithName:name andAge:age])
{
_no = no;
}
return self;
}
本文深入讲解了Objective-C中的万能指针id的概念及其使用方法,同时详细介绍了对象创建过程及构造方法的重写规范,帮助读者更好地理解Objective-C的基础概念。
6024

被折叠的 条评论
为什么被折叠?



