Вопрос

I have a strange situation which I hope someone can shed some light on. I'm implementing the NSCoding protocol in a custom object, and I'm running into memory leaks in initWithCoder:. I have something like this:

NSString* titleTemp = [aDecoder decodeObjectForKey:@"title"];
if(titleTemp) {
    [self setTitleString:titleTemp];
} else {
    [self setTitleString:[NSString string]];
}

I have lots of other properties of this object, some are arrays, some strings, and some primitives (doubles, ints), and I am consistently getting memory leaks in this method. Instruments tells me that the leak occurs in each decoding on the decodeObjectForKey: line. When you leak every single decoded object inside each custom class in an array of 10+ objects, the memory starts to add up.

But what really stumped me was that the output of this code:

NSString* titleTemp = [aDecoder decodeObjectForKey:@"title"];
NSLog(@"%i", titleTemp.retainCount);

is "3"!

Woah, where are all of those retains coming from? Beats me. But I'd love to know with all these leaks. Thanks!

Это было полезно?

Решение

Woah, where are all of those retains coming from?

It's hard to say if you can't see the code that's doing the retaining, but as long as it's not your code then you shouldn't have to worry about it. It's quite possible that -decodeObjectForKey: actually calls several other methods to create the string, and any of those might retain and subsequently autorelease that string.

Beats me. But I'd love to know with all these leaks.

Instead of trying to use -retainCount to find leaks, look at the leaked objects. Instruments can help you do that. Make sure that you're balancing your retains (and alloc, copy, and new of course) and releases for those objects. If you're over-retaining or under-releasing an object, that'll cause a leak. If some code outside your control is doing it, there's not much you can do about it anyway.

Другие советы

Read this: http://www.friday.com/bbum/2011/12/18/retaincount-is-useless/ . He's correct. What this means for you is that you need to follow Cocoa's memory management rules, while ignoring the value returned by retainCount. Make sure that you release or autorelease each object you own, either because you retained it, or because you got it from a method beginning with init, new, copy or mutableCopy. Additionally your releases/autoreleases need to be balanced with your owning references. So, if you retain an object once, you can only release it once.

In this your specific case, the problem doesn't seem to be in the small snippets you've posted. The important point though, is that you shouldn't be debugging using retainCount.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top