大家好 - 我正在编写一个非常简单的 iPhone 应用程序。数据来自一个 plist 文件(基本上是 NSDictionary),我试图将其加载到单例类中并在我的各种 View Controller 中使用它来访问数据。
这是我的单例的实现(大量模仿 this thread )
@implementation SearchData
@synthesize searchDict;
@synthesize searchArray;
- (id)init {
if (self = [super init]) {
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"searches.plist"];
searchDict = [NSDictionary dictionaryWithContentsOfFile:finalPath];
searchArray = [searchDict allKeys];
}
return self;
}
- (void)dealloc {
[searchDict release];
[searchArray release];
[super dealloc];
}
static SearchData *sharedSingleton = NULL;
+ (SearchData *)sharedSearchData {
@synchronized(self) {
if (sharedSingleton == NULL)
sharedSingleton = [[self alloc] init];
}
return(sharedSingleton);
}
@end
因此,每当我尝试访问应用程序中其他地方的 searchDict 或 searchArray 属性时(如 TableView 委托(delegate)),如下所示:
[[[SearchData sharedSearchData] searchArray] objectAtIndex:indexPath.row]
我收到一个异常说明 *** -[NSCFSet objectAtIndex:]: 无法识别的选择器发送到实例 0x5551f0
我不太确定为什么将 objectAtIndex 消息发送到 NSCFSet 对象,我觉得我的单例实现错误或其他原因。我还尝试了一个更复杂的单例实现,就像 apple 在 aforementioned thread 中推荐的那样。并有同样的问题。感谢您提供的任何见解。
最佳答案
在您的 -init
方法中,您直接访问您的实例变量,而不是保留它们。它们将被释放,它们的内存将在应用程序生命周期的后期被其他对象耗尽。
要么保留您在那里创建的对象,要么使用不方便的方法生成它们。
searchDict = [[NSDictionary alloc] initWithContentsOfFile:finalPath];
searchArray = [[searchDict allKeys] retain];
关于iphone - Objective-C 中的单例共享数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/355449/