andy boot
andy boot

Reputation: 11727

Objective C - NSString - Memory basics

I am trying to return an NSString that has been initialized from a plist.

If I comment out my release lines this code works. I would however like to release these objects from memory as I no longer need them.

I thought that 'initWithString' would copy the contents of the target string into my new string meaning I could safely release the NSMutableArray. But it isn't. Why not?

+ (NSString*) genImage {

NSString *path = [[NSBundle mainBundle] pathForResource:
                  @"Images" ofType:@"plist"];
NSMutableArray *arrayOfImages = [[NSMutableArray alloc] initWithContentsOfFile:path];

NSLog(@"%d", [arrayOfImages count]);

int indexToLoad = 0;

NSString *res = [[NSString alloc] initWithString:[arrayOfImages objectAtIndex:indexToLoad] ];

[arrayOfImages release];
[path release];
return res;

}

Upvotes: 0

Views: 141

Answers (1)

mipadi
mipadi

Reputation: 410552

You do not retain the return value of -[NSBundle pathForResource:ofType:] (the path variable), so there is no need to release it (and doing so will cause a crash, most likely). However, you should autorelease res, as you do retain that. You can change your last line to

return [res autorelease];

Upvotes: 2

Related Questions