Possible to save an integer array using NSUserDefaults on iPhone?

后端 未结 4 2052
后悔当初
后悔当初 2020-12-05 21:34

Is it possible to save an integer array using NSUserDefaults on the iPhone? I have an array declared in my .h file as: int playfield[9][11] that gets filled wi

相关标签:
4条回答
  • 2020-12-05 22:06

    Just use NSArray instead of normal C array then it will solve your problem easily.

    0 讨论(0)
  • 2020-12-05 22:08

    You'll have to convert this to an object. You can use NSArray or NSDictionary.

    0 讨论(0)
  • 2020-12-05 22:13

    From Apple's NSUserDefaults documentation:

    A default’s value must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.

    This is why you are getting the pointer error.

    You have several options (in order of recommended usage):

    1. Use an NSArray of NSArrays to store playField in your application
    2. Keep playField as an array of int, but fill an NSArray with numbers before saving to NSUserDefaults.
    3. Write your own subclass of NSArchiver to convert between an array of integers and NSData.
    0 讨论(0)
  • 2020-12-05 22:15

    You can save and retrieve the array with a NSData wrapper

    ie (w/o error handling)

    Save

    NSData *data = [NSData dataWithBytes:&playfield length:sizeof(playfield)];
    [prefs setObject:data forKey:@"slot1Save"];
    

    Load

    NSData *data = [prefs objectForKey:@"slot1Save"];
    memcpy(&playfield, data.bytes, data.length);
    
    0 讨论(0)
提交回复
热议问题