iOS指定的初始化程序:使用NS_DESIGNATED_INITIALIZER [英] iOS Designated Initializers : Using NS_DESIGNATED_INITIALIZER
问题描述
我们在XCode 6中引入了这个新的宏:NS_DESIGNATED_INITIALIZER
We have this new macro being introduced in XCode 6 : NS_DESIGNATED_INITIALIZER
我在网上搜索,但是找不到任何关于如何使用的好文档这个。
I searched on the net, but couldn't really find any good documentation as to how to use this.
从语法上讲,我们可以像以下一样使用它:
Syntactically, we can use it like :
- (instancetype)initWithCoder:(NSCoder *)coder NS_DESIGNATED_INITIALIZER;
但是使用这个宏标记初始化程序有什么可能的好处,还有什么我们可以做的事情应该在使用时查看?
But what are the possible advantages of marking an initializer with this macro, and also what are the things we should be looking at when using this ?
我主要对这个宏的用例感兴趣。任何链接/文档将不胜感激。
I am mainly interested in the use cases of this macro. Any links / documentation would be appreciated.
推荐答案
使用 NS_DESIGNATED_INITIALIZER
很好地解释了 http://useyourloaf.com/blog/2014/ 08/19 / xcode-6-objective-c-modernization.html :
指定的初始化程序保证对象完全通过向超类发送初始化消息初始化
。当
将它们子类化时,
实现细节对于类的用户变得很重要。指定初始化程序的规则详细说明:
The designated initializer guarantees the object is fully initialised by sending an initialization message to the superclass. The implementation detail becomes important to a user of the class when they subclass it. The rules for designated initializers in detail:
- 指定的初始化程序必须调用(通过super)超类的指定
初始值设定项。其中NSObject是超类,这个
只是[super init]。 - 任何便利初始化程序必须在类中调用另一个
初始化程序 - 最终会导致指定的
初始化程序。 - 具有指定初始值设定项的类必须实现超类的指定初始值设定项的所有
。
例如,如果您的界面是
@interface MyClass : NSObject
@property(copy, nonatomic) NSString *name;
-(instancetype)initWithName:(NSString *)name NS_DESIGNATED_INITIALIZER;
-(instancetype)init;
@end
然后编译器检查(方便)初始值设定项 init
调用
(指定的)初始值设定项 initWithName:
,这样会产生警告:
then the compiler checks if the (convenience) initializer init
calls
the (designated) initializer initWithName:
, so this would cause a warning:
-(instancetype)init
{
self = [super init];
return self;
}
这样就可以了:
-(instancetype)init
{
self = [self initWithName:@""];
return self;
}
在 Swift 中有关指定和便利初始化程序的规则甚至更严格,
如果你混合Objective-C和Swift代码,标记指定的Objective-C初始化器有助于编译器执行规则。
In Swift the rules about designated and convenience initializers are even more strict, and if you mix Objective-C and Swift code, marking the designated Objective-C initializers helps the compiler to enforce the rules.
例如,这个Swift子类会导致编译器错误:
For example, this Swift subclass would cause an compiler error:
class SwClass: MyClass {
var foo : String
init(foo : String) {
self.foo = foo
super.init()
}
}
这没关系:
class SwClass: MyClass {
var foo : String
init(foo : String) {
self.foo = foo
super.init(name: "")
}
}
这篇关于iOS指定的初始化程序:使用NS_DESIGNATED_INITIALIZER的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!