最近自己在寫程序的時候,想起《Effective Objective-C 2.0》中提到爲類提供“全能初始化方法”,書中代碼如下:
#import <Foundation/Foundation.h>
@interface EOCRectangle : NSObject<NSCoding>
@property (nonatomic , readonly , assign) float width;
@property (nonatomic , readonly , assign) float height;
-(id)initWithWidth:(float) width andHeight:(float) height;
@end
#import "EOCRectangle.h"
/**
* 爲對象提供必要信息以便其能完成工作的初始化方法叫做“全能初始化方法”
*/
@implementation EOCRectangle
-(id)initWithWidth:(float) width andHeight:(float) height
{
if ((self = [super init])){
_width = width;
_height = height;
}
return self;
}
/**
* 初始化設置默認的值
*/
//-(id)init
//{
// return [self initWithWidth:10.0 andHeight:10.0];
//}
/**
* 初始化拋出異常
*/
-(id)init{
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"Must use initWithWidth:(float) width andHeight:(float) height instead"
userInfo:nil];
}
/**
* 初始化NSCoding
*/
-(id)initWithCoder:(NSCoder *)aDecoder{
if ((self = [super init])){
_width = [aDecoder decodeFloatForKey:@"width"];
_height = [aDecoder decodeFloatForKey:@"height"];
}
return self;
}
@end
但在我自己寫的過程中,忘記將初始化方法名以 init 開頭,導致錯誤:
Cannot assign to 'self' outside of a method in the init family
原因:在ARC有效時,只能在init方法中給self賦值,Xcode判斷是否爲init方法規則:方法返回id,並且名字以init+大寫字母開頭+其他
爲準則。
如果此時關閉ARC,會發現剛纔的錯誤提示不見了:
如果將初始化方法名改爲 - initialize,同樣有錯誤提示,因爲不符合上面的命名規則。
這樣的命名規則是爲了保證ARC開啓時內存管理不出錯,同時,init方法必須是實例方法,並且必須返回實例對象,這樣要求的原因同上。