0

我正在使用 UISwitchs 和 UITextFields 执行此操作...

我已在头文件中将 UISwitch 声明为属性,因为我想在我的类中通过几种不同的方法访问它的值。

我正在使用以下代码将 UISwitch 添加到我的 TableViewCell 之一:

- (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;

} 

事实上,retainCounts 无处不在。将单元格放在屏幕上时,mySwitch Retain 为 2,每次我点击开关时,保留计数都会增加,直到达到 4,然后它似乎就停留在那里。

显然我错过了一些东西。如果有人能指出我正确的方向,将不胜感激。

4

2 回答 2

1

每当私有 api 与它交互时,追逐对象的 retainCount 并不是您想要做的事情。您要做的就是跟踪您自己的保留计数,然后确保您正在增加它并根据需要减少它。假设您有以下内容:

@property (nonatomic, retain) UISwitch *mySwitch;

@synthesize mySwitch;

您应该将上面的代码更改为:

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

在上面的代码中,您不再拥有 mySwitch,因为您告诉它自动释放。但是,通过使用,self.mySwitch您将在此处创建该属性时保留该属性。然后,您可以在整个程序的其余部分中随意使用它。只要确保在 dealloc 中安全地释放它。

于 2010-10-16T22:52:06.193 回答
0

1:永远,永远,永远关注retainCount返回的内容。它并不意味着是人类可解释的价值。

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

于 2010-10-16T22:54:38.360 回答