ios developer tiny share-20160905

本文讲解了Objective-C中类继承情况下初始化方法的正确实现方式。强调直接访问实例变量而非通过属性设置器,避免不确定的行为。典型初始化方法应先调用超类的初始化方法,并检查返回值是否为nil。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天讲Objective-C在类的继承情况下的初始化顺序。

Access Instance Variables Directly from Initializer Methods

Setter methods can have additional side-effects. They may trigger KVC notifications, or perform further tasks if you write your own custom methods.

You should always access the instance variables directly from within an initialization method because at the time a property is set, the rest of the object may not yet be completely initialized. Even if you don’t provide custom accessor methods or know of any side effects from within your own class, a future subclass may very well override the behavior.

A typical init method looks like this:

- (id)init {
    self = [super init];
 
    if (self) {
        // initialize instance variables here
    }
 
    return self;
}

An init method should assign self to the result of calling the superclass’s initialization method before doing its own initialization. A superclass may fail to initialize the object correctly and return nil so you should always check to make sure self is not nil before performing your own initialization.

By calling [super init] as the first line in the method, an object is initialized from its root class down through each subclass init implementation in order. Figure 3-1 shows the process for initializing an XYZShoutingPerson object.

Figure 3-1  The initialization process


As you saw in the previous chapter, an object is initialized either by calling init, or by calling a method that initializes the object with specific values.

In the case of the XYZPerson class, it would make sense to offer an initialization method that set the person’s initial first and last names:

- (id)initWithFirstName:(NSString *)aFirstName lastName:(NSString *)aLastName;

You’d implement the method like this:

- (id)initWithFirstName:(NSString *)aFirstName lastName:(NSString *)aLastName {
    self = [super init];
 
    if (self) {
        _firstName = aFirstName;
        _lastName = aLastName;
    }
 
    return self;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值