gpt4 book ai didi

iPhone 初始化方法问题

转载 作者:行者123 更新时间:2023-11-28 23:00:23 24 4
gpt4 key购买 nike

我为 NSArray 创建了一个属性,它创建了一个 getter/setter。我知道 Apple 建议在 init 和 dealloc 方法中使用实例变量。我试图弄清楚在以下代码中要做什么。

(1) 我需要额外的发布声明吗?数组不会有 2 然后 1 与 dealloc 的保留计数,留下泄漏。或者 autorelease 会处理这个问题吗?

(2) xCode 或工具中是否有某种方法可以跟踪特定变量以查看其在整个过程中的保留计数。

@property (nonatomic, retain) NSArray *array;

@synthesize arrary = _array;

- (id)initWithNibName:(NSString *)nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil
initWithArray:(NSArray *)array
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {

_array = [[NSArray alloc] initWithArray:array];

}
return self;
}

- (void)dealloc
{
[_array release];

[super dealloc];
}

最佳答案

(1) Do I need an extra release statement? Wouldn't array have a retain count of 2 then 1 with the dealloc, leave a leak. Or would autorelease take care of this?

让我们逐步完成:

@property (nonatomic, retain) NSArray *array;

// The setter in this case will do the proper ref counting:
@synthesize arrary = _array;

- (id)initWithNibName:(NSString *)nibNameOrNil
bundle:(NSBundle *)nibBundleOrNil
initWithArray:(NSArray *)array
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// _array is nil at allocation
_array = [[NSArray alloc] initWithArray:array]; // << self holds one reference

}
return self;
}

- (void)dealloc
{
[_array release]; // << self holds zero references
[super dealloc];
}

换句话说,您不需要别的了。就个人而言,我只会在初始化程序和属性中使用 copy(而不是 retain)。

(2) Is there some way in xCode or instruments to follow a specific variable to see its retain count going through the process.

是的。但是,有几个运行时快捷方式和异常(exception)情况。

最简单的方法是使用分配工具运行工具,然后启用引用计数记录。然后它将记录每个单独对象的每个引用计数的回溯和时间。

关于iPhone 初始化方法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10116338/

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