1

I would like to store some custom objects in an NSMutableArray, then store this NSMutableArray to NSUserDefaults. The custom objects look like this:

@interface myCustomClass:NSObject
{
    NSString *string1;
    NSString *string2;
    NSArray *array;
    NSURL   *URL;
}
@end

I've checked the development documentations and learned that NSUserDefaults only supports some types such as NSData, NSDate, NSString, NSArray, NSDictionary. I have searched the answer to my question for a while but haven't got a solution. Would anyone please let me know how could I save my custom objects listed above to NSMutableArray then store this array to NSUserDefaults, and how to retrieve this mutable array? Thanks a lot in advance.

stspb
  • 193
  • 2
  • 12
  • have you read [this](http://stackoverflow.com/questions/2315948/how-to-store-custom-objects-in-nsuserdefaults)? – Saran Sep 18 '11 at 05:06
  • 1
    possible duplicate of [Storing custom objects in an NSMutableArray in NSUserDefaults](http://stackoverflow.com/questions/537044/storing-custom-objects-in-an-nsmutablearray-in-nsuserdefaults) – Lily Ballard Sep 18 '11 at 05:08

1 Answers1

3

Objects that can be cached using NSUserDefaults must be property lists. If you would really like to use NSUserDefaults to cache these, then you must first implement a method that return all attributes necessary to recreate your object. This would mean a property list representation of your object, such as an NSDictionary. Think in terms of serialization/deserialization. For your case you have to ensure that your NSArray ivar in turn contains property lists only. If you can recreate NSURL using an NSString only, then save the NSString instead. You see it is getting complicated!

A much simpler approach would be to implement the NSCoding protocol in your custom class and save/retrieve your object or NSArray of objects using NSKeyedArchiver and NSKeyedUnarchiver. To implement the NSCoding protocol, you must implement only two methods initWithCoder: and encodeWithCoder:

mkumaro
  • 63
  • 6
  • 1
    Thanks a lot for your advice, mkumaro. It's not a necessity for me to use NSUserDefaults. Instead, as long as I can save the NSMutableArray filled with my custom objects into the device, and I can retrieve this NSMutableArray from the deice later on, then that will be good enough. So, I have tried using NSCoding and NSKeyedArchiver/NSKeyedUnarchiver. It works now. Thanks again, mkumaro. – stspb Sep 19 '11 at 08:56