标签:class super pre == content 打印 obj 初学 net
初学OC。对init这种方法不是非常了解。我们如今来分别对init方法进行重写以及自己定义,来加深对他的了解。
本样例也是用Person类来进行測试。
(一)重写init方法。
(1)在Person.h中声明init方法:
-(instancetype)init;
{
NSString *_peopleName;
int _peopleAge;
}
-(void)show{
NSLog(@"_peopleName = %@",_peopleName);
NSLog(@"_peopleAge = %d",_peopleAge);
}
//重写初始化方法。
- (instancetype)init
{
self = [super init];
if (self) {
_peopleName=@"Bob";
_peopleAge=24;
}
return self;
}
People *people = [[People alloc]init];
[people show];
。
(5)结果分析,输出结果成功打印出我们在init方法定义时候对成员变量的赋值。
符合预期。我们成功实现了对init方法的重写。
(二)自己定义init方法。
(1)在重写的init方法中。我们发现一个问题,我们无法在main.m中实现对init的操作。也无法通过參数传值的方式实现对成员变量的赋值。
最致命的问题是无法在实例化一个对象的时候对他拥有的成员变量赋值。
所以我们最好自己定义init方法。
首先在Person.h中声明自己定义init方法,參数包含peopleName,peopleName.
-(instancetype)initPeople: (NSString *) peopleName andAge: (int)peopleAge;
-(instancetype)initPeople:(NSString *)peopleName andAge:(int)peopleAge{
self = [super init];
if (self) {
_peopleName = peopleName;
_peopleAge = peopleAge;
}
return self;
}
People *people2 = [[People alloc]initPeople:@"Jack" andAge:26];
[people2 show];
(4)输出结果:
。
(5)结果分析,我们成功在实例化对象的时候并对其赋值,这个就是初始化方法的作用。比最初的重写init方法更为灵活。
这就和C++中的构造方法起到类似的作用。
github主页:https://github.com/chenyufeng1991 。欢迎大家訪问!
Objective-C学习笔记(二十二)——初始化方法init的重写与自己定义
标签:class super pre == content 打印 obj 初学 net
原文地址:http://www.cnblogs.com/gccbuaa/p/6885324.html