NSUserDefaults EXC_BAD_ACCESS

时间:2012-02-10 06:59:00

标签: iphone objective-c xcode

由于“onlineLastUpdatedAt”,我收到错误消息“EXC_BAD_ACCESS”,我不明白为什么。这是我的代码:

#define IMONGGO_PRODUCTS_ONLINE_LAST_UPDATED_AT_KEY @"iMonggoFetcher.ImonggoOnlineProductsLastUpdatedAt"

- (void) saveLastUpdatedAtDate{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *onlineLastUpdatedAt = [[defaults objectForKey:IMONGGO_PRODUCTS_ONLINE_LAST_UPDATED_AT_KEY] mutableCopy];
    NSString *onlineLastUpdatedAtValue = [iMonggoFetcher lastUpdatedAtDate];

    if (!onlineLastUpdatedAt) onlineLastUpdatedAt = [[NSMutableArray alloc]init];

    if([onlineLastUpdatedAt containsObject:onlineLastUpdatedAtValue]){
        NSLog(@"onlineLastUpdated at contains a value for onlineLastUpdatedatValue");
        //[defaults setObject:onlineLastUpdatedAt forKey:IMONGGO_PRODUCTS_ONLINE_LAST_UPDATED_AT_KEY];

    }else{
        NSLog(@"!onlineLastUpdated at contains a value for onlineLastUpdatedatValue");

        [onlineLastUpdatedAt addObject:onlineLastUpdatedAt];
        NSLog(@"mutablearray: %@", onlineLastUpdatedAt);
        [defaults setValue:onlineLastUpdatedAt forKey:IMONGGO_PRODUCTS_ONLINE_LAST_UPDATED_AT_KEY];
        [defaults synchronize];
    }
    NSLog(@"added to defaults: %@ ",onlineLastUpdatedAtValue);
}

2 个答案:

答案 0 :(得分:1)

当您应该致电setValue:ForKey:时,您正在致电setObject:ForKey

[defaults setValue:onlineLastUpdatedAt forKey:IMONGGO_PRODUCTS_ONLINE_LAST_UPDATED_AT_KEY];

替换为:

[defaults setObject:onlineLastUpdatedAt forKey:IMONGGO_PRODUCTS_ONLINE_LAST_UPDATED_AT_KEY];

答案 1 :(得分:-1)

您无法直接将任何对象输入NSUserDefaults 首先,您必须将该对象转换为NSDataNSMutableData 试试这个

NSData *dataVal = [NSKeyedArchiver archivedDataWithRootObject:onlineLastUpdatedAt];
[defaults setObject:dataVal forKey:IMONGGO_PRODUCTS_ONLINE_LAST_UPDATED_AT_KEY];
[defaults synchronize];