0

I have a property called data of type NSArray in InventoryFilteredTVC and here's a sample code:

NSArray *results = [array filteredArrayUsingPredicate:predicate];
NSLog(@"%i", [array retainCount]);
InventoryFilteredTVC *filteredTVC = [[InventoryFilteredTVC alloc] initWithStyle:UITableViewStylePlain];
[filteredTVC setTitle:@"Search Results"];
[filteredTVC setData:results];
NSLog(@"%i", [array retainCount]);

This returns:

1
1

Why is that? Why isn't data being retained? Also, when I try to dealloc data in dealloc method in InventoryFilteredTVC, I get a crash, which is obviously because data isn't being retained. What am I doing wrong?

EDIT: My property is defined as

@property (nonatomic, retain) NSArray *data;
sumderungHAY
  • 1,337
  • 18
  • 30

3 Answers3

3

'results' and 'array' are two different arrays. You may be retaining 'results', but why would that affect the retain count of 'array'?

As for your crash, check that you aren't releasing 'results' (it is already autoreleased), and check that you are using the synthesized setData: (or you wrote your own setData: that actually retains the data)

Firoze Lafeer
  • 17,133
  • 4
  • 54
  • 48
2

You should almost never try to understand retain counts. You'll just end up confused.

All that really matters is that you release an object as many times as you've retained it. Are you sure setData: is a retain property? Is it synthesized, or custom? Can you post it?

You're outputting the retain count of array, but you passed results to setData:. Those are different objects. If you really want to check retain counts (which, you probably shouldn't), you should check that of results.

filteredArrayUsingPredicate: returns an autoreleased object (you can tell, because the method name doesn't begin with "alloc", "new", "copy", or "mutableCopy" -- see The Docs for more info). So you should definitely be retaining it, and if setData: really is a retain property, this code should work fine.

zpasternack
  • 17,838
  • 2
  • 63
  • 81
1

Also, you shouldn't generally use the retainCount method to do memory management. I don't completely understand why, but if you want to dig deeper here's a question that might help :

When to use -retainCount?

Just use XCode's Build and Analyze and the Leaks tools to get rid of memory bugs. Don't both yourself too much with retain counts etc.

Community
  • 1
  • 1
Tejaswi Yerukalapudi
  • 8,987
  • 12
  • 60
  • 101