Question

I am doing this with UISwitchs and UITextFields...

I have declared the UISwitch as Property in the header file, because I want to access its value in several different methods within my class.

I am adding the UISwitch to one of my TableViewCells, using the following code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

mySwitch = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
cell.accessoryView = mySwitch;
mySwitch.on = YES;

return cell;

} 

As it is, the retainCounts are all over the place. The mySwitch Retain is 2 by the time the cell has been put on the screen, and every time I tap the switch, the retain count goes up, until it gets to 4, then it seems to stay there.

Obviously I am missing something. If someone can point me in the right direction, it would be greatly appreciated.

Was it helpful?

Solution

Chasing the retainCount of an object is not something that you want to do whenever private api's are interacting with it. All that you want to do is to track your own retain counts and then make sure you are incrementing it and decrementing it as necessary. Assuming you have something like the following:

@property (nonatomic, retain) UISwitch *mySwitch;

@synthesize mySwitch;

You should change your code that you have above to be this:

self.mySwitch = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
cell.accessoryView = mySwitch;
mySwitch.on = YES;

In the code you have above, you do not own mySwitch anymore as you told it to autorelease. However, by using self.mySwitch you will be retaining the property when you create it there. Then you can use it as you wish throughout the rest of the program. Just make sure to release it safely in dealloc.

OTHER TIPS

1: Never, ever, ever pay attention to what gets returned by retainCount. It is not meant to be a human interpretable value.

2: Try running build and analyze. It can find a lot of memory problems, such as this one, and explain what's wrong.

3: Every time you call alloc, you need a matching release (or autorelease). In this case, you could call [mySwitch release] after mySwitch.on = YES.

4: It pays to periodically review the memory management rules for Objective-C. http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top