使用NSKeyedArchiver将数据附加到文件

时间:2014-06-16 02:53:16

标签: ios xcode file append nskeyedarchiver

在我的程序中的某个时刻,我已经将10个对象保存到Documents目录中的文件中,使用NSKeyedArchiver对它们进行编码。

现在我想在我的文件中添加更多对象,但保留旧文件。有没有办法做到这一点?

以下是一些代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"CurriculaIndex"])
{
    curriculaIndex = [defaults objectForKey:@"CurriculaIndex"]; return YES;
}
else
    curriculaIndex = [[NSMutableArray alloc]init];

NSString *path = [[NSString stringWithFormat:@"~/Documents/Curricula"] stringByExpandingTildeInPath];
NSMutableData *dataToSave = [[NSMutableData alloc]init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:dataToSave];

int i=1; //i = curricula index
int j=1; //j = pack index
BOOL parsed = NO;

do {
    NSString *fileName = [[NSString alloc]initWithFormat:@"%i.xml", i];
    NSString *thePath = [[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:fileName];
    NSString *encoded = [[NSString alloc]initWithContentsOfFile:thePath encoding:NSUTF8StringEncoding error:nil];
    NSData *data = [encoded dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:NO];
    NSXMLParser *xmlParser = [[NSXMLParser alloc]initWithData:data];

    Parser *theParser = [[Parser alloc] initParsing];
    [xmlParser setDelegate:theParser];

    parsed = [xmlParser parse];

    if (parsed)
    {
        [curriculaIndex addObject:curriculum.name];
        [archiver encodeObject:curriculum forKey:curriculum.name];

        if (j == kMaxRegisters) 
        {
            //HERE I WOULD LIKE TO SAVE NEW OBJECTS AT THE END OF THE FILE
            j=0;
        }

        i++; j++;
        NSLog(@"Parsed properly");
    }
    else
        NSLog(@"Didn't parsed properly");
}
while (parsed);

[archiver finishEncoding];
[dataToSave writeToFile:path atomically:YES];

[defaults setObject:curriculaIndex forKey:@"CurriculaIndex"];

return YES;

}

0 个答案:

没有答案