大家好--我正在写一个非常简单的iPhone应用程序。数据来自一个plist文件(基本上是NSDictionary),我试图将它加载到一个单独的类中,并在我的各种视图控制器中使用它来访问数据。
下面是我的单例的实现(大量模仿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委托)时,如下所示:
[[[SearchData sharedSearchData] searchArray] objectAtIndex:indexPath.row]我收到一个异常,指出* -NSCFSet objectAtIndex::unrecognized选择器已发送到实例0x5551f0
我真的不确定为什么要将objectAtIndex消息发送到NSCFSet对象,我觉得我的单例实现错误或有什么问题。我还尝试了一个更复杂的单例实现,就像苹果在aforementioned thread中推荐的那样,也遇到了同样的问题。感谢您能提供的任何见解。
发布于 2008-12-10 08:59:14
在您的-init方法中,您直接访问实例变量,而不是保留它们。在应用程序的生命周期中,它们会被释放,并且它们的内存会被其他对象耗尽。
要么保留您在那里创建的对象,要么使用不方便的方法来生成它们。
searchDict = [[NSDictionary alloc] initWithContentsOfFile:finalPath];
searchArray = [[searchDict allKeys] retain];发布于 2008-12-10 14:02:21
当你赋值合成变量时,通过'self‘来赋值,所以:
- (id)init {
if (self = [super init]) {
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"searches.plist"];
self.searchDict = [NSDictionary dictionaryWithContentsOfFile:finalPath];
self.searchArray = [searchDict allKeys];
}
return self;}
另外,请确保您已将这些变量设置为“保留”在头文件中。
发布于 2009-08-03 08:49:25
嗨,你能告诉我,当我们通过'self‘赋值合成变量时,有什么好处吗?谢谢你,希瓦
这些值是通过setter设置的;它会释放先前的值,并保留您指定的值。
https://stackoverflow.com/questions/355449
复制相似问题