Reputation: 5524
I have an NSMutableArray
in which I store objects called "address". An address is an NSObject
with 4-5 properties (NSStrings
). The NSMutableArray
shall contain a maximum of 15 address object.
What is the best way to store that array on the iPhone? Core data
? NSUserDefaults
? Should I maybe store every address object by itself, and not all objects in one NSMutableArray
? In that case what should I do on the iPhone
?
Upvotes: 0
Views: 3811
Reputation: 271
Simplest way would to use the nsmutablearray read and write methods. All the data has to be plist data type nsarray nsdictionary nsstring nsnumber nsdate. Nsuserdefault like rog suggested is also good. As long as the amount of data remains small.
Upvotes: 0
Reputation: 5977
as @rog said, you may use NSUserDefaults
to save data
& you should make your object follow protocal NSCoding
for examplem if you object is "YouObject"
@interface YouObject: NSObject {
}
@property (nonatomic, copy) NSString *uid;
@property (nonatomic, copy) NSString *name;
@end
//implement this 2 method
- (id)initWithCoder:(NSCoder *)decoder {
if (self = [super init]) {
self.title = [decoder decodeObjectForKey:@"uid"];
self.author = [decoder decodeObjectForKey:@"name"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:title forKey:@"uid"];
[encoder encodeObject:author forKey:@"name"];
}
then archive or unarchive using NSUserDefaults
//archive
YouObject *object = [YouObject ....]
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:object ];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"address"];
//unarchive
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"address"];
YouObject *object = (YouObject *)[NSKeyedUnarchiver unarchiveObjectWithData:data];
or if you have a YouObject Array, you can save the NSArray in the same way;
//archive
NSArray *addresses;
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:address ];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"address"];
//unarchive
NSData *addressData = [[NSUserDefaults standardUserDefaults] objectForKey:@"address"];
NSArray *addresses = (NSArray*)[NSKeyedUnarchiver unarchiveObjectWithData:address];
Upvotes: 4
Reputation: 5361
For what you're describing, I think NSUserDefaults
will suffice. See this post: How to store custom objects in NSUserDefaults. You can learn more about the limitations of NSUserDefaults
here: What are the limitations of NSUserDefaults.
However, if you're saving/loading a large amount of data, then you should consider using Core Data.
Upvotes: 1