iphone – 指针内存管理的Cocoa策略

iphone – 指针内存管理的Cocoa策略,第1张

概述我看到很多代码,特别是在Apple示例代码中,类似于以下内容: EditingViewController *controller = [[EditingViewController alloc] initWithNibName:@"EditingView" bundle:nil]; self.editingViewController = controller; [control 我看到很多代码,特别是在Apple示例代码中,类似于以下内容:

EditingVIEwController *controller = [[EditingVIEwController alloc] initWithNibname:@"EditingVIEw" bundle:nil];    self.editingVIEwController = controller;    [controller release];

是否有任何理由特别证明上述方法对以下方法有益:

self.editingVIEwController = [[EditingVIEwController alloc] initWithNibname:@"EditingVIEw" bundle:nil];

试图了解是否有上述策略.

谢谢!

解决方法 乍一看,似乎你的例子可以工作,但事实上它会造成内存泄漏.

按照惯例,在Cocoa和Cocoa-touch中,使用[[SomeClass alloc] initX]或[SomeClass newX]创建的任何对象都是使用保留计数为1创建的.当您完成新实例时,通常在dealloc方法中,您负责调用[someClassInstance release].

当你将新对象分配给属性而不是实例变量时,这很棘手.大多数属性被定义为保留或复制,这意味着它们要么在设置时增加对象的保留计数,要么创建对象的副本,保持原始状态不变.

在您的示例中,您可能在.h文件中有此:

@property (retain) EditingVIEwController *editingVIEwController;

所以在你的第一个例子中:

EditingVIEwController *controller =     [[EditingVIEwController alloc] initWithNibname:@"EditingVIEw" bundle:nil];// (1) new object created with retain count of 1self.editingVIEwController = controller;// (2) equivalent to [self setEditingVIEwController: controller];// increments retain count to 2[controller release];// (3) decrements retain count to 1

但是对于你的第二个例子:

// (2) property setter increments retain count to 2self.editingVIEwController =     // (1) new object created with retain count of 1    [[EditingVIEwController alloc] initWithNibname:@"EditingVIEw" bundle:nil];// oops! retain count is Now 2

通过在将新对象传递给setter之前调用autorelease方法,您要求autorelease池取得对象的所有权并在将来的某个时间释放它,所以有一段时间该对象有两个所有者来匹配其保留计数一切都是笨拙的.

// (3) property setter increments retain count to 2self.editingVIEwController =     // (1) new object created with retain count of 1    [[[EditingVIEwController alloc] initWithNibname:@"EditingVIEw" bundle:nil]        // (2) give ownership to autorelease pool         autorelease];// okay,retain count is 2 with 2 owners (self and autorelease pool)

另一种选择是将新对象直接分配给实例变量而不是属性setter.假设您的代码命名为底层实例变量editingVIEwController:

// (2) assignment to an instance variable doesn't change retain counteditingVIEwController =     // (1) new object created with retain count of 1    [[EditingVIEwController alloc] initWithNibname:@"EditingVIEw" bundle:nil];// yay! retain count is 1

这是代码中的一个微妙但重要的区别.在这些示例中,self.editingVIEwController = x是[self setEditingVIEwController:x]的语法糖,但editingVIEwController是一个普通的旧实例变量,没有编译器生成的任何保留或复制代码.

另见Why does this create a memory leak (iPhone)?

总结

以上是内存溢出为你收集整理的iphone – 指针/内存管理的Cocoa策略全部内容,希望文章能够帮你解决iphone – 指针/内存管理的Cocoa策略所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1007523.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-22
下一篇2022-05-22

发表评论

登录后才能评论

评论列表(0条)

    保存