gpt4 book ai didi

objective-c - 为什么 ARC 保留方法参数?

转载 作者:行者123 更新时间:2023-12-05 06:57:11 25 4
gpt4 key购买 nike

在使用 ARC 编译时,方法参数通常表现为在方法开始时保留并在结束时释放。这个保留/释放对似乎是多余的,并且与 ARC“生成您无论如何都会编写的代码”的想法相矛盾。在那些黑暗的、ARC 之前的日子里,没有人为了安全起见对所有方法参数执行额外的保留/释放,不是吗?

考虑:

@interface Test : NSObject
@end

@implementation Test

- (void)testARC:(NSString *)s
{
[s length]; // no extra retain/release here.
}

- (void)testARC2:(NSString *)s
{
// ARC inserts [s retain]
[s length];
[s length];
// ARC inserts [s release]
}

- (void)testARC3:(__unsafe_unretained NSString *)s
{
// no retain -- we used __unsafe_unretained
[s length];
[s length];
// no release -- we used __unsafe_unretained
}

@end

当在 Release模式下使用 Xcode 4.3.2 编译时,程序集(这样我就能理解)在开始时包含对 objc_retainobjc_release 的调用并结束第二种方法。怎么回事?

这不是一个大问题,但是当使用 Instruments 分析对性能敏感的代码时,这种额外的保留/释放流量确实会出现。看起来你可以用 __unsafe_unretained 修饰方法参数来避免这种额外的保留/释放,就像我在第三个例子中所做的那样,但这样做感觉很恶心。

最佳答案

参见 this reply来自 Objc 语言邮件列表:

When the compiler doesn't know anything about the memory management behavior of a function or method (and this happens a lot), then the compiler must assume:

1) That the function or method might completely rearrange or replace the entire object graph of the application (it probably won't, but it could). 2) That the caller might be manual reference counted code, and therefore the lifetime of passed in parameters is not realistically knowable.

Given #1 and #2; and given that ARC must never allow an object to be prematurely deallocated, then these two assumptions force the compiler to retain passed in objects more often than not.

我认为主要问题是你的方法的主体可能会导致参数被释放,因此 ARC 必须采取防御措施并保留它们:

- (void) processItems
{
[self setItems:[NSArray arrayWithObject:[NSNumber numberWithInt:0]]];
[self doSomethingSillyWith:[items lastObject]];
}

- (void) doSomethingSillyWith: (id) foo
{
[self setItems:nil];
NSLog(@"%@", foo); // if ARC did not retain foo, you could be in trouble
}

这也可能是您在方法中只有一个调用时看不到额外保留的原因。

关于objective-c - 为什么 ARC 保留方法参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64949085/

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