views:

148

answers:

1

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;
    }

gary

+2  A: 

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;
}
Nick Forge
Many thanks Nick, also thank you for the pointers on the correct formatting. Much appreciated.
fuzzygoat