开发者

error when releasing object

-(void)LoadOriginalListFromFile
{

NSMutableArray *temp;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *path = [documentsDirectory stringByAppendingPathComponent:@"shopes.dat"];
//2.check if file exists
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:path]) 
{
    //open it and read it 
    NSLog(@"shopes.dat file found. reading into memory");
    NSMutableData *theData;
    NSKeyedUnarchiver *decoder;
    //3. decode the file into memory
    theData = [NSData dataWithContentsOfFile:path];
    decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData];
    temp = [[NSMutableArray alloc]init];
    temp = [decoder decodeObjectForKey开发者_如何学编程:@"m_OriginalArray"];

    //4. add object to original list
    NSEnumerator *enumerator = [temp objectEnumerator];
    id anObject;

    while (anObject = [enumerator nextObject]) 
    {

        [m_OriginalArray addObject:anObject];
    }

    //[temp release];   // here is the problem!!!!!
    [decoder finishDecoding];
    [decoder release];

}
else
{
    NSLog(@"shopes.dat file not found");
}

}

I have problem with the temp object. what i want to do is to release the object before the function end but if i do so when the app is launch i get ERROR_BAD_ACSS , i cant understand why? i alloc the temp object then i add all the objects in the temp array to my m_OriginalArray i also tryied to retain the objects but no lack.


You allocate the object here:

temp = [[NSMutableArray alloc]init];

but then immediately replace it with a difference object returned from the NSKeyedUnarchiver:

temp = [decoder decodeObjectForKey:@"m_OriginalArray"];

The new object will be autoreleased, so there is no need to release it. You can simply remove the first line (the NSMutableArray alloc & init one) completely, as you are not using that object.


You're creating "temp" twice here. First you're alloc/init'ing it, in which case the release would make sense. But then that instance is getting discarded, and replaced with the return value from [decoder decodeObjectForKey: @"m_originalArray"]. That new instance is autoreleased, and so when you release it manually, you're setting it up to crash when the autorelease pool drains. Simply get rid of the first assignment, and the matching release, and you won't leak or crash.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜