将对象添加到NSArray时程序崩溃



我设置了以下IBAction

#define FAVORITES_KEY @"GraphViewController.Favorites"
- (IBAction)addToFavorites:(id)sender {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *favorites = [defaults objectForKey:FAVORITES_KEY];
    if (!favorites) favorites = [NSMutableArray array];
    [favorites addObject:self.program];
    [defaults setObject:favorites forKey:FAVORITES_KEY];
    [defaults synchronize];
}

第一次调用这个操作时,一切都很好,对象被添加到我的数组中并保存到NSUserDefaults,没有任何问题,在第一次调用后,它将在添加到favorites数组时抛出异常,如果我试图跳过中断,它会说:

Single stepping until exit from function objc_exception_throw, 
which has no line number information.
Catchpoint 3 (exception thrown).

有人有类似的问题,或者可能知道发生了什么?

NSUserDefaults返回一个不可变的数组,因此需要对其进行转换:

NSMutableArray *favorites = [[defaults objectForKey:FAVORITES_KEY] mutableCopy];
if (!favorites) favorites = [NSMutableArray new];
...
[favorites release];

最新更新