Attempt to set a non-property-list object as an NSUserDefaults

前端 未结 11 1628
闹比i
闹比i 2020-11-22 15:00

I thought I knew what was causing this error, but I can\'t seem to figure out what I did wrong.

Here is the full error message I am getting:

Attempt to se         


        
11条回答
  •  北海茫月
    2020-11-22 15:43

    The code you posted tries to save an array of custom objects to NSUserDefaults. You can't do that. Implementing the NSCoding methods doesn't help. You can only store things like NSArray, NSDictionary, NSString, NSData, NSNumber, and NSDate in NSUserDefaults.

    You need to convert the object to NSData (like you have in some of the code) and store that NSData in NSUserDefaults. You can even store an NSArray of NSData if you need to.

    When you read back the array you need to unarchive the NSData to get back your BC_Person objects.

    Perhaps you want this:

    - (void)savePersonArrayData:(BC_Person *)personObject {
        [mutableDataArray addObject:personObject];
    
        NSMutableArray *archiveArray = [NSMutableArray arrayWithCapacity:mutableDataArray.count];
        for (BC_Person *personObject in mutableDataArray) { 
            NSData *personEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:personObject];
            [archiveArray addObject:personEncodedObject];
        }
    
        NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
        [userData setObject:archiveArray forKey:@"personDataArray"];
    }
    

提交回复
热议问题