3

嘿伙计们 - 我正在编写一个非常简单的 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

因此,每当我尝试访问应用程序中其他地方的 searchDict 或 searchArray 属性(如 TableView 委托)时,如下所示:

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

我收到一个异常说明 *** -[NSCFSet objectAtIndex:]: unrecognized selector sent to instance 0x5551f0

我不太确定为什么将 objectAtIndex 消息发送到 NSCFSet 对象,我觉得我的单例实现错误或其他什么。我还尝试了一种更复杂的单例实现,就像苹果在上述线程中推荐的那样,并且遇到了同样的问题。感谢您提供的任何见解。

4

3 回答 3

11

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

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

searchDict = [[NSDictionary alloc] initWithContentsOfFile:finalPath];
searchArray = [[searchDict allKeys] retain];
于 2008-12-10T08:59:14.233 回答
1

每当您分配合成变量时,请通过“自我”进行,因此:

- (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;

}

还要确保您已将这些变量设置为“保留”在头文件中。

于 2008-12-10T14:02:21.297 回答
0

嗨,你能告诉我当我们通过'self'分配合成变量时有什么优势吗?谢谢湿婆

这些值是通过设置器设置的;它释放先前的值并保留您分配的值。

于 2009-08-03T08:49:25.213 回答