在我看来,您提供了一个带有额外代码的类。我会尽力解释。
首先,在您的上一个中,您有两个不同的IBOutlet。我想第一个是你加的。
IBOutlet UISegmentedControl *disp;
第二个是 Xcode 在您进行拖放操作时添加的。
@property (retain, nonatomic) IBOutlet UISegmentedControl *displaySlider;
首要考虑
IBOutlet 一词只是 Xcode 的占位符。通过它,Xcode 可以帮助您将实例变量连接到图形元素。
当我使用出口连接时,我通常会提供像 @property (retain, nonatomic) IBOutlet UISegmentedControl *displaySlider; 这样的访问器(就像 Xcode 所做的那样),因为如果不这样做,您可能会出现内存泄漏问题。
二次考虑
Xcode 提供的代码是正确的。当您进行拖动操作时,您将displayController 实例变量与您的图形元素相关联。为了平衡这种连接,必须在 dealloc 方法中释放该实例变量,如下所示:
[displayController release];
为了成瘾,Xcode 添加了[self setDisplaySlider:nil];,因为在内存警告情况下可以调用viewDidUnload 方法。这里没有问题,因为当控制器再次加载到内存中时,插座连接会恢复。
两种方法调用的区别可以在Advanced Memory Management doc和release-or-set-to-nil-retained-members中读取。请注意,如果您这样做:
[displayController release];
您可以直接访问名为displayController 的实例变量,而如果您这样做:
[self setDisplaySlider:nil]; // or self.displaySlider = nil;
您访问该实例变量的访问器(在本例中为 setter 方法)。不一样(为避免混淆,请参阅我提供的代码)。
所以,这是我将使用的代码(我添加了一些 cmets 来指导您):
//.h
@interface ViewController : UIViewController
{
UISegmentedControl *disp; // instance variable called disp
// (A) now this is no longer necessary, new compile mechanism will create an instance
// variable called _displaySlider under the hood
}
@property (retain, nonatomic) IBOutlet UISegmentedControl *displaySlider;
@end
//.m
@synthesize displaySlider = disp; // I say to Xcode to create a setter and a getter to access the instance variable called disp as written in @property directive
// no longer necessary for (A)
- (void)viewDidUnload
{
[super viewDidUnload];
[self setDisplaySlider:nil]; // I call the setter method to release the UISegmentedControl
}
- (void)dealloc {
[disp release]; // I release the UISegmentedControl directly
// if you choose the (A) mechanism simply do
// [_displaySlider release];
[super dealloc];
}
希望对你有帮助。