Reputation: 7764
Right now on my iPhone application I'm saving a large chunk of data from a NSData
object to NSUserDefaults
. I know that's not the best approach because NSUserDefaults
is meant only to store small pieces of data.
I'm doing this something like this:
NSData *data = [NSData alloc]init]];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"MyData"];
For late retrieval of this data.
What's the correct way to save this data
permanently for further use?
Upvotes: 0
Views: 145
Reputation: 6803
Make a custom class with the properties you want (.h file):
#import <Foundation/Foundation.h>
@interface CustomHolder : NSObject {
NData *data;
}
@property (strong, nonatomic) NSData *data;
@end
And then set the .m file up so that you can encode/decode the object
#import "CustomHolder.h"
@implementation CustomHolder
@synthesize data;
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:data forKey:@"data"];
}
- (id)initWithCoder:(NSCoder *)decoder
{
if (self = [super init])
{
self.data = [decoder decodeObjectForKey:@"data"];
}
return self;
}
@end
Then you can just [NSKeyedArchiver archiveRootObject:obj toFile:[self saveFilePath]]
to save and [NSKeyedUnarchiver unarchiveObjectWithFile:[self saveFilePath]]
to load.
This works for any kind of data, and gives you the option of adding as many different data files as you need to an object.
Upvotes: 2
Reputation: 407
NSUserDefaults are handy for small amounts of data, not complex data structures There is no real 'permanent' way of saving data unless you have an external server that stores it, but Core Data is a good way of storing is on the device as long as the application doesn't get deleted.
This tutorial by Ray Wenderlich is a good starting point. Takes you through NSManagedObject concepts, fetchRequests etc. There's several parts to it so you can incrementally build your data schema
Good luck
Upvotes: 1