问题描述
在您的一个Objective-C类中实现+初始化或+加载方法时,是否应始终以此类保护开始
When implementing an +initialize or +load method in one of your Objective-C classes, should you always start with this kind of guard?:
@implementation MyClass
+ (void)initialize {
if (self == [MyClass class]) {
...
}
}
...
@end
看起来像+ load和+ initialize中的代码通常只想执行一次。因此,当子类加载/初始化时,这将有助于避免dupe执行。
Seems like code in +load and +initialize usually only wants to be executed once. So this would help avoid dupe execution when subclasses load/initialize.
我想我只是想从一些ObjC向导强化这是必要的/通常做法。 。
I guess I'm just wanting some reinforcement from some ObjC wizards that this is necessary/common practice...
这是什么常识?你会建议你总是这样做吗?
What's the common wisdom on this? would you recommend always doing this?
你的建议对于+ load和+ initialize是一样的,还是他们应该处理的方式有区别?
Is your advice the same for both +load and +initialize, or is there a difference in they way they should be handled?
感谢。
推荐答案
是的,您应该在您的初始化如果你正在初始化全局变量只应该初始化一次的方法。
Yes, you should do this in your intialize and load methods if you are initializing globals that should only be initialized once.
也就是说,有很多情况下你可以避免它...
That said, there are a number of cases where you may avoid it...
如果需要对每个类的每个继承执行工作,则不应使用此条件包装:
You shouldn't wrap with this conditional if the work needs to be performed on every inheritant of every class:
- 例如,将每个类的所有继承类名添加到集合中。
- 编辑的添加或者您正在建立KVO依赖关系
- For example, adding all inherited class names for each class to a set.
- edited addition: or you're establishing KVO dependencies (as mentioned by eJames)
还有一些情况下,您只需要不必费心:
There are also situations where you just needn't bother:
- 如果您执行的操作是幂等的(如果重复则不要更改值)
- )
幂等部分是相关的。初始化器应该只是设置初始状态(每次都应该相同)。在一个好的初始化程序中,重复不要紧。虽然我想如果你忘记在条件中将方法包装在 有问题,这可能很讨厌。
The "idempotent" part is relevant. An initializer should just be setting the initial state (which should be the same each time). In a good initializer, repetition shouldn't matter. Although I suppose that if you forget to wrap the method in the conditional when it does matter, this might be annoying.
编辑添加:一种不同的方法,正确反映任何初始化只有一次的要求是测试您的初始化属性是否已初始化。即
edited addition: A different approach, that properly reflects any initialize-only-once requirements would be to test if your properties to initialize are initialized already. i.e.
id myGlobalObject = nil;
+(void)initialize
{
if (myGlobalObject == nil)
{
myGlobalObject = [[MyGlobalClass alloc] init];
}
}
这篇关于应该+初始化/ +加载总是以一个开始:if(self == [MyClass class])guard?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!