使用NSUSERDEFAULTS

时间:2016-02-25 09:48:40

标签: ios objective-c xcode nsmutablearray nsuserdefaults

我正在尝试在NSUserDefaults中保存NSMutableArray。这是我的代码

(void) alarmSetting :(AlarmObject *)alarmObject
{

    [alarmSelect addObject:alarmObject];

    time = alarmObject.clockDate;
    title = alarmObject.titleForAlarm;
    repeat = alarmObject.repeatData;
    video = alarmObject.titleOfTheVideo;
    double uniqueId = alarmObject.uniqueTime;
    ID = [NSNumber numberWithDouble:uniqueId];


    if(![[NSUserDefaults standardUserDefaults] objectForKey:@"MyAlarms"])
    {
        alarmToBeSaved= [[NSMutableArray alloc] init];

    }
    else
    {

        alarmToBeSaved=[[NSUserDefaults standardUserDefaults] valueForKey:@"MyAlarms"] ;

    }

   [alarmToBeSaved addObject:alarmObject];
    [[NSUserDefaults standardUserDefaults] setObject: alarmToBeSaved forKey:@"MyAlarms"];
    NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"MyAlarms"]);
    [[NSUserDefaults standardUserDefaults] synchronize];

    [tbleView reloadData];

}

但我收到错误

016-02-25 14:40:05.003 Alarm[3229:87627] Attempt to set a non-property-list object (
    "<AlarmObject: 0x7ff4807ecd80>"
) as an NSUserDefaults/CFPreferences value for key MyAlarms
2016-02-25 14:40:05.054 Alarm[3229:87627] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object (
    "<AlarmObject: 0x7ff4807ecd80>"
) for key MyAlarms'

为什么会这样?我搜索了这个错误,我不明白因为我在NSUserDefaults中保存了一个数组。

1 个答案:

答案 0 :(得分:0)

您发布的代码尝试将一组自定义对象保存到NSUserDefaults。当然,你不能这样做。实现NSCoding方法没有帮助,您只能在NSUserDefaults中存储NSArray,NSDictionary,NSString,NSData,NSNumber和NSDate等内容。

首先,您需要将对象转换为NSData,然后将该NSData存储在NSUserDefaults中。如果需要,您甚至可以存储NSData的NSArray。

当您回读数组时,您需要取消归档NSData以获取BC_Person对象。这是NSKeyedArchiver的逆过程。

保存

NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:yourObject];
[currentDefaults setObject:data forKey:@"yourKeyName"];

获取

NSData *data = [currentDefaults objectForKey:@"yourKeyName"];
yourObjectType * token = [NSKeyedUnarchiver unarchiveObjectWithData:data];
For Remove

[currentDefaults removeObjectForKey:@"yourKeyName"];

希望有所帮助:)