Reputation: 9
I have a NSMutableArray feed.leagues which has two objects of <MLBLeagueStandings: 0xeb2e4b0>
I want to write it to a file and then read it from the file. This is what I have done:
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:feed.leagues forKey:@"feed.leagues"];
}
- (id)initWithCoder:(NSCoder *)decoder {
if (self = [super init]) {
self.feed.leagues = [decoder decodeObjectForKey:@"feed.leagues"];
}
return self;
}
-(void)saveJSONToCache:(NSMutableArray*)leaguesArray {
NSString *cachePath = [self cacheJSONPath];
[NSKeyedArchiver archiveRootObject:feed.leagues toFile:cachePath];
NSMutableArray *aArray = [NSKeyedUnarchiver unarchiveObjectWithFile:cachePath];
NSLog(@"aArray is %@", aArray);
}
-(NSString*)cacheJSONPath
{
NSString *documentsDirStandings = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *cacheJSONPath = [NSString stringWithFormat:@"%@/%@_Standings.plist",documentsDirStandings, sport.acronym];
return cacheJSONPath;
}
Upvotes: 0
Views: 238
Reputation: 1661
Your object : MLBLeagueStandings should be serializable and respond to NSCoding protocole :
@interface MLBLeagueStandings : NSObject <NSCoding>{
}
Now in your MLBLeagueStandings class file (.m) add the following methods :
- (id)initWithCoder:(NSCoder *)decoder;
{
self = [super initWithCoder:decoder];
if(self)
{
yourAttribute = [decoder decodeObjectForKey:@"MY_KEY"]
//do this for all your attributes
}
}
- (void)encodeWithCoder:(NSCoder *)encoder;
{
[encoder encodeObject:yourAttribute forKey:@"MY_KEY"];
//do this for all your attributes
}
In fact if you want to write an object to a file (in your case it's an array), all the object contained in this array have to conform to the NSCoding protocole.
Moreover if you want example : here is a good tutorial
Hope it will help you.
NB : if you want to encode/decode primitive type (int, float etc...) use :
[encode encodeInt:intValue forKey:@"KEY"];
(more information on apple doc)
Upvotes: 1