简体   繁体   中英

unarchiveObjectWithFile retain / autorelease needed?

Just a quick memory management question if I may ... Is the code below ok, or should I be doing a retain and autorelease, I get the feeling I should. But as per the rules unarchiveObjectWithFile does not contain new , copy or alloc .

-(NSMutableArray *)loadGame {
    if([[NSFileManager defaultManager] fileExistsAtPath:[self pathForFile:@"gameData.plist"]]) {
        NSMutableArray *loadedGame = [NSKeyedUnarchiver unarchiveObjectWithFile:[self pathForFile:@"gameData.plist"]];
        return loadedGame;
    } else return nil;
}

or

-(NSMutableArray *)loadGame {
        if([[NSFileManager defaultManager] fileExistsAtPath:[self pathForFile:@"gameData.plist"]]) {
            NSMutableArray *loadedGame = [[NSKeyedUnarchiver unarchiveObjectWithFile:[self pathForFile:@"gameData.plist"]] retain];
            return [loadedGame autorelease];
        } else return nil;
    }

You are correct in that unarchiveObjectWithFile returns an autoreleased object, since it doesn't contain new , copy or alloc .

Here's a version that is slightly re-written to use common Objective-C formatting idioms:

- (NSMutableArray *)loadGame {
    NSString *gameDataPath = [self pathForFile:@"gameData.plist"];
    if([[NSFileManager defaultManager] fileExistsAtPath:gameDataPath]) {
        return [NSKeyedUnarchiver unarchiveObjectWithFile:gameDataPath];
    }
    return nil;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM