How to protect objects from autorelease?
Finally the objective-c memory management caught me. I'm fighting with a problem now for 2 days. I´m new to Objective C and can't solve the problem by my own. Seems like I am unknowingly overreleasing an Object. If I´m doin the zombie analysis I´m getting the "An Objective-C message was sent to a deallocated object.."
This is the important part of the Analysis Log I guess: The last line with RefCt -1 shows the responsible caller is -[XClass dataset]
dataset is a NSDictionary that I use to store data of every object. Im Using the Dictionary in two ex开发者_如何学编程tern classes by using the 2 methods of XClass ("updateDictionary:" and "dict:")
The Declaration of the File:
XClass.h: ... NSDictionary* dataset; ... @property (retain) NSDictionary *dataset; - (id)initWithDeviceValue:(NSDictionary*)DataSet - (void) updateDictionary:(NSDictionary *)dict; - (NSDictionary *)dict;
XClass.m: @synthesize dataset; -(id)initWithDeviceValue:(NSDictionary*)DataSet{ .. if (self = [super init]) { dataset = DataSet;} } return self; } - (void) updateDictionary:(NSDictionary *)dict{ dataset=[NSDictionary dictionaryWithDictionary:dict]; } -(NSDictionary *)dict{ return dataset; }
The first extern method calling the (dict:) function gets the actual dictionary correctly. The second function doesn't get the dictionary because it seems to be released!
Like I said the last line of the zombie log is:
Malloc: Zombie RefCt: -1 Responsible caller is -[XClass dataset]
The former interesting lines:
Line 2 of the Zombielog:
Malloc:CFRetain RefCt:2 Responsible Caller:-[XClass dataset]
Line 3 of the Zombielog:
Malloc:Autorelease RefCt:empty Responsible Caller:-[XClass dataset]
It seems like the dictionary of my object got autoreleased. Maybe because it had the RefCt (retain count?) of 2 which was too much and so got autoreleased? How can I prevent objects from being autoreleased?
XClass.m: try this ...
@synthesize dataset;
-(id)initWithDeviceValue:(NSDictionary*)DataSet{
..
if (self = [super init])
{
self.dataset = DataSet;
}
return self;
}
- (void) updateDictionary:(NSDictionary *)dict{
self.dataset=[NSDictionary dictionaryWithDictionary:dict];
}
-(NSDictionary *)dict{
return dataset;
}
@pawan.mangal
Problem solved! It´s all about the good old retainCount. When I initialize the new Objects from Xclass I have to add a retain like [code][[XClass objectx]retain][/code]
in order to keep it alive for more than one request.
Also I deleted both methods from the class and let the synchronised getters and setters do the work.
The retainCount of the object decreases by 1 every time I´m using its automatically generated accessor (the getter in this case) . Right?
精彩评论