0

我有一个 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;
}
4

1 回答 1

1

您的对象: MLBLeagueStandings 应该是可序列化的并响应 NSCoding 协议:

@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 协议。

此外,如果您想要示例:这是一个很好的教程

希望它会帮助你。

注意:如果您想对原始类型(int、float 等)进行编码/解码,请使用:

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

有关苹果文档的更多信息

于 2012-10-22T06:34:38.863 回答