安全地将对象作为ARC下的不透明上下文参数传递 [英] Passing objects safely as opaque context params under ARC

查看:112
本文介绍了安全地将对象作为ARC下的不透明上下文参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在手动内存管理下,我经常使用这种模式:

Under manual memory management, I use this pattern fairly often:

NSString * myStr = /* some local object */
[UIView beginAnimation:@"foo" context:(void *)[myStr retain]];

然后,以后和异步:

- (void)animationDidStop:(NSString *)anim finished:(NSNumber *)num context:(void *)context
{
    NSString * contextStr = (NSString *)context;
    // ...
    [contextStr release];
}

我手动管理用作不透明上下文的对象的生命周期。 (这对于旧的UIView动画也是如此,但也适用于我使用的其他类型的API。)

i.e. I manually managed the lifetime of an object used as an opaque context. (This is true for the old UIView animations but also for other kinds of API that I use.)

在ARC下,我的本能是我想要 __ bridge_retained ,并在处理程序中插入 __ bridge_transfer 如这里所建议的。但是这把一个Cocoa对象视为 CFType ,不是因为它真的被桥接,而是为了推出一个保持下来的喉咙。

Under ARC, my instinct is that I want to __bridge_retained going in and __bridge_transfer in the handler, as suggested here. But this treats a Cocoa object as a CFType not because it's really bridged, but just for the purpose of shoving a retain down its throat.

这是有效的,这是风格上可接受的吗?如果没有,什么是更好的解决方案?

Is this valid, and is this stylistically acceptable? If not, what's the better* solution?

(接受的答案在这个问题中给出了不同的答案,说单独的 __ bridge 是可以的,但是在我看来是错误的,因为原始的字符串将有风险是吗?)

(The accepted answer in this question gives a different answer, saying that __bridge alone is OK, but that seems to me to be wrong, since the original string would be at risk of being deallocated as soon as it goes out of scope in the first function. Right?)

*请不要说使用基于块的动画。 (这不是我的问题。)

*Please don't say "use block-based animations instead". (That's not what I'm asking about.)

推荐答案

去与你的直觉。 __ bridge_retained 从ARC传输一个对象的管理给你,而 __ bridge_transfer 反过来,不用担心处理对象作为 CFType - 你不是真的这样做只是接管管理。

Go with your instinct. __bridge_retained transfers management of an object to you from ARC, while __bridge_transfer does the reverse, don't worry about treating the object as a CFType - you're not really doing that just taking over management.

推荐是构建你的代码,使ARC保留管理,但这可以很容易地遇到作为设计(和得到凌乱)。拥有您使用的API维护的价值,因为它是设计做的是干净的;只是在管理交给API并返回给ARC的地方适当地注释代码。

The other approach you see recommended is to construct your code so that ARC retains management, but this can easily come across as contrived (and get messy). Having the API you're using maintain the value as it is designed to do is clean; just comment the code appropriately where management is handed to the API and returned back to ARC.

这篇关于安全地将对象作为ARC下的不透明上下文参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆