首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Objective-C中的单例共享数据源

Objective-C中的单例共享数据源
EN

Stack Overflow用户
提问于 2008-12-10 08:49:44
回答 3查看 17.9K关注 0票数 3

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

下面是我的单例的实现(大量模仿this thread)

代码语言:javascript
运行
复制
@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委托)时,如下所示:

代码语言:javascript
运行
复制
[[[SearchData sharedSearchData] searchArray] objectAtIndex:indexPath.row]

我收到一个异常,指出* -NSCFSet objectAtIndex::unrecognized选择器已发送到实例0x5551f0

我真的不确定为什么要将objectAtIndex消息发送到NSCFSet对象,我觉得我的单例实现错误或有什么问题。我还尝试了一个更复杂的单例实现,就像苹果在aforementioned thread中推荐的那样,也遇到了同样的问题。感谢您能提供的任何见解。

EN

Stack Overflow用户

回答已采纳

发布于 2008-12-10 08:59:14

在您的-init方法中,您直接访问实例变量,而不是保留它们。在应用程序的生命周期中,它们会被释放,并且它们的内存会被其他对象耗尽。

要么保留您在那里创建的对象,要么使用不方便的方法来生成它们。

代码语言:javascript
运行
复制
searchDict = [[NSDictionary alloc] initWithContentsOfFile:finalPath];
searchArray = [[searchDict allKeys] retain];
票数 11
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/355449

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档