将NSMutableArray写入文件然后读取它

时间:2012-10-22 06:07:12

标签: iphone objective-c ios nsmutablearray

我有一个NSMutableArray feed.leagues有两个<MLBLeagueStandings: 0xeb2e4b0>对象 我想将它写入文件,然后从文件中读取它。这就是我所做的:

- (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;
}

1 个答案:

答案 0 :(得分:1)

您的对象:MLBLeagueStandings应该可序列化并响应NSCoding protocole:

@interface MLBLeagueStandings : NSObject <NSCoding>{

}

现在,在您的MLBLeagueStandings类文件(.m)中添加以下方法:

- (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
}

实际上,如果你想将一个对象写入一个文件(在你的情况下它是一个数组),这个数组中包含的所有对象必须符合NSCoding protocole。

此外,如果您想要示例:here is a good tutorial

希望它会对你有所帮助。

注意:如果你想编码/解码原始类型(int,float等...),请使用:

[encode encodeInt:intValue forKey:@"KEY"];

more information on apple doc

相关问题