Objective-C

构造方法

2019-02-21  本文已影响16人  越天高

1.重写init方法

想在对象创建完毕后,成员变量马上就有一些默认的值就可以重写init方法

重写init方法格式:

- (id)init {
    self = [super init];
    if (self) {
        // Initialize self.
    }
    return self;
}
// 重写init方法, 在init方法中初始化成员变量
// 注意: 重写init方法必须按照苹果规定的格式重写, 如果不按照规定会引发一些未知的错误
// 1.必须先初始化父类, 再初始化子类
// 2.必须判断父类是否初始化成功, 只有父类初始化成功才能继续初始化子类
// 3.返回当前对象的地址
- (instancetype )init
{  // 1.初始化父类
    // 只要父类初始化成功 , 就会返回对应的地址, 如果初始化失败, 就会返回nil
    // nil == 0 == 假 == 没有初始化成功
    self = [super init];
    // 2.判断父类是否初始化成功
    if (self != nil) {
        // 3.初始化子类
        // 设置属性的值
        _age = 6;
        
    }
    // 4.返回地址
    return self;
}

2.练习

@implementation Person

- (instancetype)init
{
    if (self = [super init]) {
        _age = 10;
    }
    return self;
}
@end

3.构造方法使用注意

4.instancetype的作用

// init此时返回值是id
NSString *str = [[Person alloc] init];
// Person并没有length方法, 但是id是动态类型, 所以编译时不会报错
NSLog(@"length = %i", str.length);
// init此时返回值是instancetype
// 由于instancetype它会进行类型检查, 所以会报警告
NSString *str = [[Person alloc] init];
NSLog(@"length = %i", str.length);
instancetype *p = [[person alloc] init];
// 错误写法instancetype只能作为返回值

自定义构造方法

1.自定义构造方法

自定义构造方法的规范

(1)一定是对象方法,以减号开头
(2)返回值一般是instancetype类型
(3)方法名必须以initWith开头

@interface Person : NSObject

@property int age;

@property NSString *name;

// 当想让对象一创建就拥有一些指定的值,就可以使用自定义构造方法
- (id)initWithAge:(int)age;

- (id)initWithName:(NSString *)name;

- (id)initWithAge:(int)age andName:(NSString *)name;

@end

继承中的自定义构造方法

@interface Person : NSObject

@property int age;

- (id)initWithAge:(int)age;
@end



@interface Student : Person

@property NSString *name;

- (id)initWithAge:(int)age andName:(NSString *)name;
@end

@implementation Student

- (id)initWithAge:(int)age andName:(NSString *)name
{
    if (self = [super init]) {
//        这个_Age是父类中通过property自动在.m中生成的无法继承,不能直接访问
//        _age = age;
        [self setAge:age];
        _name = name;
    }
    return self;
}
@end
@interface Person : NSObject

@property int age;

- (id)initWithAge:(int)age;
@end



@interface Student : Person

@property NSString *name;

- (id)initWithAge:(int)age andName:(NSString *)name;
@end

@implementation Student

- (id)initWithAge:(int)age andName:(NSString *)name
{
    if (self = [super initWithAge:age]) {
        _name = name;
    }
    return self;
}
@end
initsuper.png

2.自定义构造方法的使用注意

上一篇下一篇

猜你喜欢

热点阅读