Pregunta

I am trying to save my object to the file system on an iPad, but I seem to be doing something wrong. Here is how I have archived the object:

NSString *localizedPath = [self getPlistFilePath];
NSString *fileName = [NSString stringWithFormat:@"%@.plist", character.infoName];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:character];

fileName = [fileName stringByReplacingOccurrencesOfString:@" " withString:@"_"];
localizedPath = [localizedPath stringByAppendingPathComponent:fileName];

NSLog(@"File Path: %@", localizedPath);

if(data) {
    NSError *writingError;

    BOOL wasWritten = [data writeToFile:localizedPath options:NSDataWritingAtomic error:&writingError];

    if(!wasWritten) {
        NSLog(@"%@", [writingError localizedDescription]);
    }
}

Now, this creates a plist file that I can see and read on the file system. When I try to use the following to unarchive it though:

NSError *error;
NSString *directory = [self getPlistFilePath];
NSArray *files = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:directory error:&error];
NSMutableArray *characters = [[NSMutableArray alloc]init];

for(NSString *path in files) {
    if(![path hasSuffix:@"plist"]) {
        continue;
    }
    NSString *fullPath = [directory stringByAppendingPathComponent:path];
    NSData *data = [NSData dataWithContentsOfFile:fullPath];
    IRSkillsObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:data]; // get EXEC_BAD_ACCESS here...
    [data release];

    [characters addObject:object];
}

I get an EXEC_BAD_ACCESS error.

The IRSkillsObject conforms to the NSCoding protocol. You can see, I commented the line that I get the error on.

I am sure it's something I am doing wrong, but I just can't see it. I have tried to step through with the debugger (placing a break point in the initWithCoder: method of the object) but I don't get any errors then. In fact, it places the data in the object properly as I watch. But once it's done loading the data, it gives the error. I have tried using the retain method, but that doesn't help.

Any help that you can provide would be greatly appreciated!

¿Fue útil?

Solución

When an EXEC_BAD_ACCESS error is found. Usually is because some data has been released but it is still needed in the code.

Maybe there is a property inside your IRSkillsObject not retained in -initWithCoder:

Otros consejos

You are releasing data without allocating it.

NSData *data = [NSData dataWithContentsOfFile:fullPath];
IRSkillsObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[data release];

So try this:

NSData *data = [[NSData alloc] initWithContentsOfFile:fullPath];
IRSkillsObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[data release];    
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top