iOS内存pipe理问题

当您使用Xcode的function并从nib文件拖动到.h和.m文件时,Xcode将代码添加到deallocviewDidUnload 。 它增加了我通常不会添加的额外代码。 我只是好奇,如果这个额外的代码是必要的。

我会做[self setDisplaySlider:nil]而不是disp = nil[disp release]

这是必要的吗? 我不认为你必须发布显示。

 @interface ViewController : UIViewController { IBOutlet UISegmentedControl *disp; } @property (retain, nonatomic) IBOutlet UISegmentedControl *displaySlider; @end - (void)viewDidUnload { [self setDisplaySlider:nil]; [disp release]; disp = nil; [super viewDidUnload]; } - (void)dealloc { [displaySlider release]; [disp release]; [super dealloc]; } 

在我看来,你提供了一个额外的代码类。 我会尽力解释。

首先,在你之前你有两个不同的IBOutlet 。 我想第一个是你加的。

 IBOutlet UISegmentedControl *disp; 

第二个,而不是,当您进行拖放操作时已被Xcode添加。

 @property (retain, nonatomic) IBOutlet UISegmentedControl *displaySlider; 

首先考虑

术语IBOutlet只是Xcode的占位符。 通过它,Xcode可以帮助你将一个实例variables连接到一个graphics元素。

当我使用sockets连接我通常提供一个访问器像@property (retain, nonatomic) IBOutlet UISegmentedControl *displaySlider; (正如Xcode所做的那样),因为如果不是的话,你可能会导致内存泄漏问题。

第二个考虑

Xcode提供的代码是正确的。 当你进行拖动操作时,你可以使用graphics元素链接到displayController实例variables。 为了平衡这个连接,这个实例variables必须在像下面这样的dealloc方法中被释放:

 [displayController release]; 

另外,Xcode增加了[self setDisplaySlider:nil]; 因为在内存警告情况下,可以调用viewDidUnload方法。 这里没有问题,因为当控制器再次加载到内存中时,sockets连接被恢复。

两个方法调用之间的区别可以在高级内存pipe理文档和释放或设置为零保留的成员中读取。 请注意,如果你这样做:

 [displayController release]; 

你直接访问你的实例variables叫做displayController ,而如果你这样做:

 [self setDisplaySlider:nil]; // or self.displaySlider = nil; 

您访问该实例variables的访问器(在这种情况下是setter方法)。 这是不一样的(避免混淆,看我提供的代码)。

所以,这是我会使用的代码(我添加了一些评论来指导你):

 //.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]; } 

希望能帮助到你。

看看你的viewDidLoad:我想你会发现对象被分配在那里。

你需要在viewDidUnload中使用release来平衡它,否则如果视图被重新加载,对象将被重新分配,而不会被释放,你会泄漏。