KVO leaks memory
KVO leaks memory
- Subject: KVO leaks memory
- From: Andreas Grosam <email@hidden>
- Date: Fri, 24 Apr 2009 23:55:59 +0200
I get strange memory leaks when I use KVO. The setup of all classes is
OK as far as I can see, and the KVO is actually working. There is no
memory leak when the classes will be tested in test cases without KVO.
There are two classes involved:
class Model and class Observer
Model has a property port where observer listens for change events.
The leak only occurs when KVO actually sends a change event.
Otherwise, there are no leaks, even when KVO is established but no
message has been sent. So it is quite probable that the source of the
leak is within KVO code. The object leaking is obviously the receiver
for the addObserver message, namely the model.
The leak is always only for one object and plus all the objects that
are retained by model, no matter how often instances of Model will be
created and KVO established.
For instance, doing this in a loop: creating observer and model,
establish KVO, then causing a KVO event, tearing down everything --
will only produce one leak from object model (plus the leaks from
retained objects).
Here is the code for the observer that adds itself as an observer who
listens at property "port" of model.
@implementation Observer
- (void) registerObserver
{
[model addObserver:self forKeyPath:@"port"
options:NSKeyValueObservingOptionNew context:NULL];
}
Here is the notification method for observer:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void
*)context
{
NSDate *date = [NSDate date];
NSString *formattedDateString = [dateFormatter
stringFromDate:date];
NSLog(@"%@: %@", formattedDateString, keyPath);
}
The model spawns a thread who's run method installs a NSTimer in the
RunLoop. The timer handler then finally changes the value of property
port of model. When the work is done, it is ensured, that the thread
exits properly and releases all retained objects. After the thread
function has been exited, the observer model and the observer will be
released.
Note: The notification method observeValueForKeyPath will be invoked
in a different thread than the main thread, where the KVO has been
established.
The application runs currently in a Unit Test as a test case from the
google toolbox for mac, on the iPhone. When the test case finishes,
all objects should be deallocated.
So, what do I see here? Any thoughts what could cause the leaks?
Thanks for help
Regards
Andreas
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden