Objective-C中的单例共享数据源 [英] Singleton shared data source in Objective-C

查看:86
本文介绍了Objective-C中的单例共享数据源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好-我正在编写一个非常简单的iPhone应用程序.数据来自一个plist文件(基本上是NSDictionary),我正在尝试将其加载到singleton类中,并在各种视图控制器中使用它们来访问数据.

Hey folks - I'm writing a pretty simple iPhone application. The data comes from a plist file (NSDictionary basically), that I'm trying to load into a singleton class and use across my various view controllers to access the data.

这是我单身人士的实现(严格按照此线程)

Here's the implementation for my singleton (heavily modeled after 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

因此,每当我尝试在应用程序中其他位置(如TableView委托)访问searchDict或searchArray属性时,都这样:

So whenever I try to access the searchDict or searchArray properties elsewhere in my application (like a TableView delegate) like so:

[[[SearchData sharedSearchData] searchArray] objectAtIndex:indexPath.row]

我收到一个异常说明***-[NSCFSet objectAtIndex:]:无法识别的选择器发送到实例0x5551f0

I get an exception stating *** -[NSCFSet objectAtIndex:]: unrecognized selector sent to instance 0x5551f0

我不太确定为什么将objectAtIndex消息发送到NSCFSet对象,我觉得我的单例实现错误或其他原因.我还尝试了一种更复杂的单例实现,例如前面提到的线程,并且存在相同的问题.感谢您提供的任何见解.

I'm not really sure why the objectAtIndex message is being sent to an NSCFSet object, I feel like my singleton is implemented wrong or something. I also tried a more complex singleton implementation like the one recommended by apple in the aforementioned thread and had the same problem. Thanks for any insight you can provide.

推荐答案

在您的-init方法中,您直接访问实例变量,但没有保留它们.它们将被释放,并且它们的内存将在应用程序的生存期内被其他对象占用.

In your -init method you are directly accessing your instance variables and you are not retaining them. They're getting deallocated and their memory is being used up by other objects later on in your application's lifetime.

要么保留要在其中创建的对象,要么使用非便捷方法生成它们.

Either retain your objects that you're creating there or use the non-convenience methods to generate them.

searchDict = [[NSDictionary alloc] initWithContentsOfFile:finalPath];
searchArray = [[searchDict allKeys] retain];

这篇关于Objective-C中的单例共享数据源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆