gpt4 book ai didi

iphone - 用于指针/内存管理的 Cocoa 策略

转载 作者:太空狗 更新时间:2023-10-30 03:58:08 24 4
gpt4 key购买 nike

我看到很多代码,尤其是在 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 .当您完成新实例时,您负责调用 [someClassInstance release],通常是在您的 dealloc 方法中。

当您将新对象分配给属性而不是实例变量时,这会变得棘手。大多数属性被定义为 retaincopy,这意味着它们要么在设置时增加对象的保留计数,要么制作对象的副本,保持原始不变。

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

@property (retain) EditingViewController *editingViewController;

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

EditingViewController *controller = 
[[EditingViewController alloc] initWithNibName:@"EditingView" bundle:nil];
// (1) new object created with retain count of 1

self.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 2
self.editingViewController =

// (1) new object created with retain count of 1
[[EditingViewController alloc] initWithNibName:@"EditingView" bundle:nil];

// oops! retain count is now 2

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

// (3) property setter increments retain count to 2
self.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 count
editingViewController =

// (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 策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/574029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com