I have a custom object called Occasion defined as follows:
#import <Foundation/Foundation.h>
@interface Occasion : NSObject {
NSString *_title;
NSDate *_date;
NSString *_imagePath;
}
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSDate *date;
@property (nonatomic, retain) NSString *imagePath;
Now I have an NSMutableArray of Occasions which I want to save to NSUserDefaults. I know it's not possible in a straight forward fashion so I'm wondering which is the easiest way to do that? If serialization is the answer, then how? Because I read the docs but couldn't understand the way it works fully.
NSUserDefaults
is intended for user preferences, not storing application data. Use CoreData or serialize the objects into the documents directory. You'll need to have your class implement theNSCoding
protocol for it to work.1) Implement
NSCoding
inOccasion.h
2) Implement the protocol in
Occasion.m
3) Archive the data to a file in documents directory
4) To unarchive...
You should use something like
NSKeyedArchiver
to serialize the array to anNSData
, save it to theNSUserDefaults
and then useNSKeyedUnarchiver
to deserialize it later:You will need to implement the
NSCoding
protocol in yourOccasion
class and correctly save the various properties to make this work correctly. For more information see the Archives and Serializations Programming Guide. It shouldn't be more than a few lines of code to do this. Something like:You could implement
NSCoding
inOccasion
.You then use
[NSKeyedArchiver archivedDataWithRootObject:myArray]
to create anNSData
object from the array. You can put this into user defaults.