0

This is my code where I reloads particular sections of _collectionView. When I check memory leaks using Leaks template in Xcode 6.3 Instruments, it shows leak on line

[_collectionView reloadSections:indexToLoad];

and _NSCFNumber as a leaked object. Here is my code:

NSMutableIndexSet* indexToLoad = [NSMutableIndexSet new];
for (NSInteger index in array) {
    if (index != NSNotFound) {
        [indexToLoad addIndex:index];
    }
}
if (indexToLoad.count > 0) {
    [_collectionView reloadSections:indexToLoad];
}

As I read somewhere, "the leaks instrument shows you where a leak was allocated but doesn't show you the line of code that caused the leak", how can I found a cause of leak? Also how to fix this leak?

NOTE: ARC is enabled for class in which this code is running(whole project is ARC enabled). Also this code is running on main thread.

Thanks for answers in advance :)

  • 1
    There is no line where a leak occurs. A leak occurs when all references to that object go out of scope but no one bothered to collect the object. In your case, your code doesn't even compile to begin with, so can you show us the actual code that you are having issues with? – JustSid Jul 09 '15 at 15:02
  • Really, show us the code that is actually running. If that code compiles, then you really need to turn on some compiler warnings. – gnasher729 Jul 09 '15 at 23:59

1 Answers1

1

I notice that you are iterating an array and casing its contents to NSInteger. As you can't add NSInteger to an Objective-C array I'm going to assume that that's an array of NSNumber's which just happens to be the class which is leaking.

When you add an object (e.g. NSNumber) to a collection (i.e. NSArray, NSSet e.t.c) the collection creates a STRONG reference to that object. That means that when that NSNumber falls out of scope ARC or a garbage collector won't come along and release it. This can cause some problems however, one being retain cycles.

What I suspect is happening (I can't be sure without actually testing your full code) is that when the NSMutableIndexSet falls out of scope ARC comes along and tries to release all the NSNumber objects that it contains but finds it cannot as they are still retained by the array. If not then somewhere in code you are hanging on to one or more NSNumber instances and ARC doesn't like it.

Solution: ARC is not a panacea when it comes to memory management. It makes memory management much more friendly and because of that people tend to assume that they can write any code they like and ARC will take care of the rest. You still need to be aware of your references (strong vs weak) and when to use each one. Also make sure you know what the default state is; for example @property NSNumber *num; is the equivalent of @property (nonatomic, strong) NSNumber *num;

Rob Sanders
  • 5,197
  • 3
  • 31
  • 58