ios Objective-C init 方法的正确语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4165872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct syntax for Objective-C init method
提问by eclux
Why doesn't this common property initialization scheme risk failure when the synthesized setter tries to release the undefined myArray object? Or are property objects automatically initialized to nil and I don't need to be doing this at all?
当合成的 setter 尝试释放未定义的 myArray 对象时,为什么这种常见的属性初始化方案不会冒失败的风险?或者属性对象是否自动初始化为 nil 而我根本不需要这样做?
@interface myClass : NSObject {
NSArray* myArray;
}
@property (nonatomic, retain) NSArray* myArray;
@end
@implementation myClass
@synthesize myArray;
-(id)init {
if ( self = [super init] ) {
self.myArray = nil;
}
return self;
}
...
采纳答案by paulbailey
As others have stated, the instance variable is already initialised to nil
.
正如其他人所说,实例变量已经初始化为nil
.
Additionally, as per Apple's documentation, instance variables should be set directly in an init
method, as the getter/setter methods of a class (or subclass thereof) may rely on a fully initialised instance.
此外,根据 Apple 的文档,实例变量应直接在init
方法中设置,因为类(或其子类)的 getter/setter 方法可能依赖于完全初始化的实例。
回答by Barry Wark
Object instance variables in Objective-C are initialized to nil
by default. Furthermore, messaging nil
is allowed (unlike calling a method on null
in function-calling languages like Java, C# or C++). The result of a message to nil
is nil
, this calling [nil release];
is just nil
, not an exception.
Objective-C 中的对象实例变量nil
默认被初始化。此外,nil
允许消息传递(与null
在 Java、C# 或 C++ 等函数调用语言中调用方法不同)。消息的结果nil
是nil
,此调用[nil release];
只是nil
,而不是异常。
On a side note, it's best practice to assign/call instance variables directly in -init
and -dealloc
methods:
附带说明一下,最佳做法是直接在-init
和-dealloc
方法中分配/调用实例变量:
-(id)init {
if ( self = [super init] ) {
myArray = nil;
}
return self;
}
- (void)dealloc {
[myArray release];
[super dealloc];
}
回答by F'x
It's already initialized to nil
.
它已经初始化为nil
.