And*_*ssa 3 iphone singleton objective-c
嘿伙计们 - 我正在写一个非常简单的iPhone应用程序.数据来自plist文件(基本上是NSDictionary),我正在尝试加载到单例类中,并使用我的各种视图控制器来访问数据.
这是我的单例的实现(在此线程之后重新建模)
@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
Run Code Online (Sandbox Code Playgroud)
所以每当我尝试访问我的应用程序中的其他地方的searchDict或searchArray属性时(如TableView委托),如下所示:
[[[SearchData sharedSearchData] searchArray] objectAtIndex:indexPath.row]
Run Code Online (Sandbox Code Playgroud)
我得到一个异常说明*** - [NSCFSet objectAtIndex:]:无法识别的选择器发送到实例0x5551f0
我不太确定为什么objectAtIndex消息被发送到NSCFSet对象,我觉得我的单例实现错误或者什么.我也尝试了一个更复杂的单例实现,就像上面提到的线程中苹果推荐的那样,并且遇到了同样的问题.感谢您提供的任何见解.
Ash*_*ark 11
在您的-init方法中,您直接访问实例变量,而不是保留它们.它们正在被解除分配,并且它们的内存在应用程序的生命周期中被其他对象用完.
保留您在那里创建的对象,或使用非便利方法生成它们.
searchDict = [[NSDictionary alloc] initWithContentsOfFile:finalPath];
searchArray = [[searchDict allKeys] retain];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17826 次 |
| 最近记录: |