为什么这段代码会给我一个关于弱属性的错误?

发布于 2025-01-08 18:13:53 字数 464 浏览 0 评论 0原文

这是我在 iOS 上使用 ARC 编写的简单代码:

@interface Person : NSObject {
    NSObject *objStrong;
    NSObject *objWeek;
}
@property(strong) NSObject *objStrong;
//getting error at this line
@property(weak) NSObject *objWeek; //Existing ivar 'objWeek' for _week property 'objWeek' must be _week 

@end

@implementation Person
@synthesize objStrong;
@synthesize objWeek;

@end

当我尝试编译时,编译器抱怨 _weak 属性“objWeek”的现有 ivar“objWeek”。为什么这段代码不能正确编译?

This is my simple piece of code on iOS, using ARC:

@interface Person : NSObject {
    NSObject *objStrong;
    NSObject *objWeek;
}
@property(strong) NSObject *objStrong;
//getting error at this line
@property(weak) NSObject *objWeek; //Existing ivar 'objWeek' for _week property 'objWeek' must be _week 

@end

@implementation Person
@synthesize objStrong;
@synthesize objWeek;

@end

When I try to compile, the compiler complains about an existing ivar 'objWeek' for _weak property 'objWeek'. Why isn't this code compiling correctly?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

累赘 2025-01-15 18:13:53

它会抱怨,因为支持变量 NSObject *objWeek 被声明为 __strong (所有其他未注释的指向可保留对象的 Objective C 指针都是 __strong)。将支持变量更改为 __weak NSObject *objWeek,编译器将再次喜欢您。

编辑:根据要求,来自 LLVM clang 的 ARC 文档:

4.4.1。对象

如果一个对象被声明为可保留的对象所有者类型,但是
如果没有显式的所有权限定符,其类型是隐式的
调整为具有__strong资格。

作为一种特殊情况,如果对象的基类型是 Class(可能是
协议限定),类型调整为具有 __unsafe_unretained
相反,资格。

链接:http://clang.llvm.org/docs/AutomaticReferenceCounting.html#ownership.inference

It's complaining because the backing variable, NSObject *objWeek is declared as __strong (all otherwise unannotated Objective C pointers to retainable objects are __strong). Change the backing variable to be __weak NSObject *objWeek, and the compiler will like you again.

Edit: As requested, the ARC documentation from LLVM's clang:

4.4.1. Objects

If an object is declared with retainable object owner type, but
without an explicit ownership qualifier, its type is implicitly
adjusted to have __strong qualification.

As a special case, if the object's base type is Class (possibly
protocol-qualified), the type is adjusted to have __unsafe_unretained
qualification instead.

Link: http://clang.llvm.org/docs/AutomaticReferenceCounting.html#ownership.inference

陌伤浅笑 2025-01-15 18:13:53

我也遇到过同样的问题。我确实花了很多时间在这上面,最后我可以通过清理项目来解决这个问题。这就是方法....

product->clean

原因是你可能被删除了控制器类(ViewController),但它仍然没有被删除从您的项目中删除。当您完成项目清理后,错误将自动消失。这对我有用......

Same problem I have faced. I did spend lot of time on this finally I could solve this problem by cleaning the project.Here is the way....

product->clean

The reason is you may be deleted controller class(ViewController) but still it is not removed from your project.when you finish cleaning of your project the error will be gone automatically. This worked for me...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文