Objective-C学习笔记(二十二)——初始化方法init的重写与自己定义

      初学OC。对init这种方法不是非常了解。我们如今来分别对init方法进行重写以及自己定义,来加深对他的了解。

本样例也是用Person类来进行測试。

(一)重写init方法。

(1)在Person.h中声明init方法:

-(instancetype)init;

(2)在Person.m中声明成员变量。以及写一个打印成员变量的函数,而且重写init初始化方法:在重写的方法中。对成员变量进行了赋值。注意,这个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;
}

(3)在main.m中调用该重写的init方法,并进行打印成员变量的值。

        People *people  = [[People alloc]init];
        [people show];
        

(4)输出结果例如以下:


(5)结果分析,输出结果成功打印出我们在init方法定义时候对成员变量的赋值。

符合预期。我们成功实现了对init方法的重写。


(二)自己定义init方法。

(1)在重写的init方法中。我们发现一个问题,我们无法在main.m中实现对init的操作。也无法通过參数传值的方式实现对成员变量的赋值。

最致命的问题是无法在实例化一个对象的时候对他拥有的成员变量赋值。

所以我们最好自己定义init方法。

      首先在Person.h中声明自己定义init方法,參数包含peopleName,peopleName.

-(instancetype)initPeople: (NSString *) peopleName andAge: (int)peopleAge;

(2)在Person.m中实现init方法。使用传入的參数值对成员变量进行赋值:

-(instancetype)initPeople:(NSString *)peopleName andAge:(int)peopleAge{

    self = [super init];
    if (self) {
        _peopleName = peopleName;
        _peopleAge = peopleAge;
    }
    return self;
}

(3)在main.m中实例化对象,在实例化对象的同一时候进行成员变量的赋值,然后信息打印:

People *people2 = [[People alloc]initPeople:@"Jack" andAge:26];

[people2 show];

(4)输出结果:


(5)结果分析,我们成功在实例化对象的时候并对其赋值,这个就是初始化方法的作用。比最初的重写init方法更为灵活。

这就和C++中的构造方法起到类似的作用。


github主页:https://github.com/chenyufeng1991  。欢迎大家訪问!

原文地址:https://www.cnblogs.com/gccbuaa/p/6885324.html