__strong和__weak关键字放置-Objective-C [英] __strong and __weak keyword placement - Objective-C

查看:95
本文介绍了__strong和__weak关键字放置-Objective-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译器似乎对以下两个声明没有问题:

The compiler seems to have no problem with the two following declarations:

NSObject * __weak weakThing;
__weak NSObject *anotherWeakThing;

两者之间有区别吗?行为类似于 const关键字?

Is there a difference between the two? Is the behavior like the const keyword?

我问是因为Xcode的警告通常暗示...

I ask because Xcode's warning generally suggest ...

SomeDataType * __弱/__强

SomeDataType * __weak / __strong

...当您搞砸了一些东西时.因此,我尝试遵循这种模式,但想知道是否存在任何区别.

... when you've goofed something up. So I've tried to follow this pattern, but wondered if there was a difference at all.

推荐答案

不,没有区别.使用const关键字,可以在声明中应用多种内容.它可以应用于指针,也可以应用于所指向的值.

No, there is no difference. With the const keyword, there are multiple things it could apply to in a declaration; it could apply to the pointer, or it could apply to the value being pointed to.

所有权限定符仅对指向对象的指针有意义.对象本身不能是强"或弱".它是指向强弱对象的指针. ARC仅在直接应用于指针到对象的类型时才有意义,并且会影响指针的生存期如何影响对象的生存期.

Ownership qualifiers only make sense on pointers to objects. The object itself can't be "strong" or "weak"; it's the pointer to the object that is strong or weak. ARC only makes sense when applied directly to pointer-to-object types, and affects how that pointer's lifetime will affect the lifetime of the object.

鉴于所有权限定符可能适用于什么没有任何歧义,ARC规范允许将所有权限定符放置在指针到对象的定义中的任何位置.您的两个示例都同样有效.同样,以下所有内容都表示同一件事:

Given that there is never any ambiguity about what the ownership qualifier could apply to, the ARC specification allows placement of the ownership qualifier anywhere in the definition of the pointer-to-object. Both of your examples are equally valid. Likewise, all of the following mean the same thing:

NSError * __autoreleasing * someObject;
NSError __autoreleasing ** someObject;
__autoreleasing NSError ** someObject;

请注意,尽管如此,编译器仍会抱怨:

Note that the compiler complains about this one, though:

NSError ** __autoreleasing someObject;

这是因为您已经超出了指向对象的指针的定义.您可以将其解析为(NSError *)* __autoreleasing someObject;.到第二个*时,您已经定义了指针的类型,因此__autoreleasing没有任何意义.指针类型定义中的任何位置都可以,但是一旦移至指针到指针类型,就意味着要引用其他内容,这不再有意义.

This is because you've moved beyond the definition of the pointer-to-object. You could parse that one as (NSError *)* __autoreleasing someObject;. By the time you get to the second *, you've already defined the type of the pointer, so __autoreleasing doesn't make any sense. Anywhere within the definition of the pointer type is fine, but once you move onto the pointer-to-pointer type, then you're referring to something else, and it no longer makes sense.

这篇关于__strong和__weak关键字放置-Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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