Question

I'am new to Xcode and I really need help on this.

I'm trying to use Archiving to save a file with an array of items and trying to read and put them in a table view.

The problem is that when I close the app and then launch it again, when I save the data into the file it overwrites the existing file and all the stored data goes away.

I'm using this methods to store data in the file:

-(id)init
{

    if(self = [super init])
    {
        _appSupportPath = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES)lastObject];

        if (!_appSupportPath)
            return nil;

        _repositoryPath = [_appSupportPath stringByAppendingPathComponent:FILE_NAME];

        if (_data == nil)
            _data = [[NSMutableDictionary alloc] init];
    }
    return self;
}

-(void)saveToFile
{

    dispatch_queue_t writeQueue = dispatch_queue_create("MyApp:file:write", NULL);

    NSMutableDictionary *localData = [NSMutableDictionary dictionaryWithDictionary:_data];

    dispatch_async(writeQueue, ^{
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if(![fileManager fileExistsAtPath:_appSupportPath])
            [fileManager createDirectoryAtPath:_appSupportPath withIntermediateDirectories:YES attributes:nil error:NULL];
        [NSKeyedArchiver archiveRootObject:localData toFile:_repositoryPath];
    });

}

Any help?

Please let me know if there's a better/easier way of storing files that I'm not aware of.

Thanks in advance

Était-ce utile?

La solution

You save it correctly. Read it on launch in the init:

_data = [[NSKeyedUnarchiver unarchiveObjectWithFile:_repositoryPath] retain];

if (_data == nil)
    _data = [[NSMutableDictionary alloc] init];
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top