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

标签 iphone objective-c singleton

大家好 - 我正在编写一个非常简单的 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/

相关文章:

objective-c - 接口(interface)定义在ios示例代码中重复

c++ - boost python 导出单例

java - 如何在java中创建一个对象的五个实例,以便当引用该对象时,这五个实例应该像对象池一样?

java - 不可变类/对象,私有(private)构造函数,工厂方法

ios - 连接两个文本字段,以便在一个文本字段中输入值会导致更改另一个文本字段的值

iphone - UItextView iOS 7 问题

iphone - 以编程方式添加 UIButton 时出现 UITableView 错误

javascript - window.close() 在 iOS 上不起作用

ios - 如何在sqlite数据库的表行中添加NSDictionary

objective-c - -(BOOL)trackMouse :inRect:ofView:untilMouseUp: Is never invoked