默认初始化方法的过程

13 篇文章 0 订阅
13 篇文章 0 订阅
创建一个类的对象时,一定要调用它们的默认初始化器或者指定的初始化器进行初始化

具体:创建一个 Monkey 继承自NSObject 的类,定义3个实例变量
#import <Foundation/Foundation.h>

@interface Monkey : NSObject
- (id)initWithWeight: (int)weight;
- (id)initWithWeight:(int)weight height:(int)height;
- (id)initWithWeight:(int)weight height:(int)height gender:(int)gender;
@end


@interface Monkey ()
{
    int _weight;
    int _height;
    int _gender;
}
@end

@implementation Monkey
- (id)init
{
    self = [self initWithWeight:0 height:0 gender:0];
    
    return self;
}

- (id)initWithWeight:(int)weight
{
    self = [self initWithWeight:weight height:0 gender:0];
    
    return self;
}

- (id)initWithWeight:(int)weight height:(int)height
{
    self = [self initWithWeight:weight height:height gender:0];
    
    return self;
}

//Default initializer/Designated initializer
- (id)initWithWeight:(int)weight height:(int)height gender:(int)gender
{
    self = [super init];
    if (self) {
        _weight = weight;
        _height = height;
        _gender = gender;
    }
    
    return self;
}
@end

在创建一个DeadMonkey 继承自Monkey
#import <Foundation/Foundation.h>

#import "Monkey.h"

@interface DeadMonkey : Monkey

@end

@implementation DeadMonkey
- (id)initWithWeight:(int)weight height:(int)height gender:(int)gender
{
    self = [super initWithWeight:10 height:10 gender:10];
    if (self) {
        
    }
    
    return self;
}
@end

再去调用这初始化方法观察
Monkey *monkey1 = [[Monkey alloc] initWithWeight: 20 height:30];
    
    默认初始化方法的使用
 DeadMonkey *deadMonkey = [[DeadMonkey alloc] init];

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值