jde*_*dee 0 objective-c nsmutablearray
我在网上找到了这段代码.它以我以前从未见过的方式设置NSMutableArray(我是一个Obj-C newb).有人可以解释它在做什么以及为什么你会这样做?特别是方法签名上的@syncronized,static和little加号.
add the following to the .h file:
+(NSMutableArray *)allMySprites;
add the following to he .m file after implementation:
static NSMutableArray * allMySprites = nil;
+(NSMutableArray *)allMySprites {
@synchronized(allMySprites) {
if (allMySprites == nil)
allMySprites = [[NSMutableArray alloc] init];
return allMySprites;
}
return nil;
Run Code Online (Sandbox Code Playgroud)
}
添加到其他响应...发布的代码是错误的.它应该更像是这样的:
@implementation SpriteManager
+ (NSMutableArray*) allMySprites {
@synchronized(self) {
if (allMySprites == nil) {
allMySprites = [[NSMutableArray alloc] init];
}
}
return allMySprites;
}
@end
Run Code Online (Sandbox Code Playgroud)
在nil上@synchronize没有任何意义.在类方法中使用self指的是类而不是实例.原始代码中的'return nil'也毫无意义.
可以完全避免使用@synchronized的更好方法是使用类初始化方法:
@implementation SomeClass
+ (void) initialize
{
allMySprites = [[NSMutableArray alloc] init];
}
@end
Run Code Online (Sandbox Code Playgroud)
保证在使用类之前调用initialize方法.
| 归档时间: |
|
| 查看次数: |
3240 次 |
| 最近记录: |