释放NSKeyedUnarchiver时,[CFString release]会导致崩溃

时间:2011-04-25 02:19:15

标签: ios objective-c cocoa-touch

+(id)decodeObjectForKey:(NSString *)key fromFile:(NSString *)fileName
{
    NSData* data = [[NSData alloc] initWithContentsOfFile:[self dataFilePath:fileName]];
    NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    id object = [unarchiver decodeObjectForKey:key];
    [unarchiver finishDecoding];

    [data release];
#warning  some trouble here!!
    [unarchiver release];   
    return object;
}

这是我的app_delegate中的一个函数,但是当我调用它时,程序会崩溃并给出这样的注释:

-[CFString release]: message sent to deallocated instance 0x4e63a60

我不知道我在哪里向CFString发送了一个版本?

PS:dataFilePath函数:

+(NSString*)dataFilePath:(NSString*) appdix
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    return [documentsDirectory stringByAppendingPathComponent:appdix];
}

1 个答案:

答案 0 :(得分:0)

decodeObjectForKey返回一个自动释放的对象。我认为您应该保留此对象并在使用后稍后将其释放..

你的 decodeObjectForKey函数中......此处不做更改..

//no change here..
id object = [unarchiver decodeObjectForKey:key];
...
return object;

现在当你使用你的 decodeObjectKey函数时,保留它返回的值

id returnedObject = [[yourAppDelegate decodeObjectForKey:@"yourKey" fromFile:@"yourFile"]retain];
//do whatever you need with this variable..
......
...
//after your usage..
[returnedObject release];

希望这会有所帮助..