使用哪种同步方法来确保单例仍然是单例?
+(Foo*)sharedInstance
{
@synchronized(self)
{
if (nil == _sharedInstance)
{
_sharedInstance = [[Foo alloc] init];
...
}
}
return _sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)
还是使用互斥?
#import <pthread.h>
static pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;
+(Foo*)sharedInstance
{
pthread_mutex_lock(&_mutex);
if (nil == _sharedInstance)
{
_sharedInstance = [[Foo alloc] init];
...
}
pthread_mutex_unlock(&_mutex);
return _sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)
嗯..对此有何评论?
singleton multithreading memory-management objective-c thread-safety
我是Objective C业务的新手(大部分时间都是Java开发人员),现在正在使用我的第一个杀手级应用程序.:-)目前我对选择器作为方法参数的使用感到困惑.例如,他们似乎与C#中的代表有点不同.
给出以下方法签名
-(void)execute:(SEL)callback;
Run Code Online (Sandbox Code Playgroud)
有没有办法强制执行传递给这种方法的选择器的签名?该方法期望具有以下签名的方法的选择器
-(void)foo:(NSData*)data;
Run Code Online (Sandbox Code Playgroud)
但SEL(类型)是通用的,因此很有可能将错误的选择器传递给 execute方法.好吧,至少在运行时,人们会看到一个有趣的行为......但我希望在发生这种情况时看到编译器警告/错误.
我再一次在我的代码中寻找内存泄漏和其他疯狂错误.:)
我有一个常用文件的缓存(图像,数据记录等,TTL大约一周,大小限制缓存(100MB)).目录中有时超过15000个文件.在应用程序退出时,缓存会写入一个控制文件,其中包含当前缓存大小以及其他有用信息.如果应用程序由于某种原因崩溃(有时会发生),我在这种情况下计算应用程序启动时所有文件的大小,以确保我知道缓存大小.我的应用程序崩溃,因为内存不足,我不知道为什么.
内存泄漏检测器根本不显示任何泄漏.我也没有看到.下面的代码有什么问题?有没有其他快速的方法来计算iPhone上目录中所有文件的总大小?也许没有枚举目录的全部内容?代码在主线程上执行.
NSUInteger result = 0;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDirectoryEnumerator *dirEnum = [[[NSFileManager defaultManager] enumeratorAtPath:path] retain];
int i = 0;
while ([dirEnum nextObject]) {
NSDictionary *attributes = [dirEnum fileAttributes];
NSNumber* fileSize = [attributes objectForKey:NSFileSize];
result += [fileSize unsignedIntValue];
if (++i % 500 == 0) { // I tried lower values too
[pool drain];
}
}
[dirEnum release];
dirEnum = nil;
[pool release];
pool = nil;
Run Code Online (Sandbox Code Playgroud)
谢谢,MacTouch