Reputation: 10039
In my TaggingScreen.m init function, I do -
tags = [myTagMgr getMyTags];
In my getMyTags method, I do the following -
NSMutableDictionary *myTags = [NSMutableDictionary new];
....
return myTags;
I get a memory leak for myTags in this method. Where should I release the memory? "tags" is a property which is used throughout the TaggingScreen class. So if I do an autorelease, I get an exception saying "message sent to deallocated instance" when I try to access tags in other methods of the class.
EDIT:
- (NSMutableDictionary *)getMyTags
{
NSMutableDictionary *myTags=[NSMutableDictionary new];
NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init]autorelease];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Tag"
inManagedObjectContext:localObjectContext];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedArrayObjects = [localObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedArrayObjects ==nil) {
return nil;
}
if ([fetchedArrayObjects count]==0) {
return nil;
}
Tag *aMessage;
for (int i=0; i<[fetchedArrayObjects count];i++)
{
aMessage= (Tag *)[fetchedArrayObjects objectAtIndex:(NSUInteger)i];
[myTags setValue:[aMessage isSet] forKey:[aMessage tagName]];
}
return myTags;
}
Upvotes: 0
Views: 260
Reputation: 16725
Vignesh and Vin's solutions are correct, but based on what you've said, the best thing to do would be to change tags
into a strong
property:
@property (nonatomic, strong) NSMutableDictionary *tags;
Unless you're in a situation where a retain loop might arise (say, a delegate object), you should use strong
so your properties aren't deallocated from under you.
In addition, unless you're using ARC, you'll want to autorelease myTags
:
return [myTags autorelease];
Oh, and if you're not using ARC, you'll want to make sure to release tags
in dealloc
.
Upvotes: 1
Reputation: 33428
if you do it in init
method you can do the following:
tags = [[myTagMgr getMyTags] retain];
instead in your getMyTags
method
return [myTags autorelease];
In this manner you have +1 for your NSDictionary
and you can access it with self.tags
within your controller.
where
@property (nonatomic, retain) NSDictionary* tags;
Remember to release it in dealloc
- (void)dealloc
{
[tags release]; tags = nil;
[super dealloc];
}
P.S. I'm assuming you don't use ARC.
Upvotes: 1
Reputation: 10251
You should autorelease
in the method. If you need it you will have to retain
it where you call it.
tags = [[myTagMgr getMyTags] retain];
Upvotes: 0