繁体   English   中英

Objective-C ARC属性重新声明混淆

[英]Objective-C ARC property redeclaration confusion

我有以下代码:

// MyObject.h
#import <Foundation/Foundation.h>

@interface MyObject : NSObject
@property (nonatomic, readonly) id property;
@end

// MyObject.m
#import "MyObject.h"

@interface MyObject ()
@property (nonatomic, copy, readwrite) id property;
@end

@implementation MyObject
@synthesize property = _property;
@end

这会生成以下编译器警告和错误:

warning: property attribute in continuation class does not match the primary class
@property (nonatomic, copy, readwrite) id property;
^
note: property declared here
@property (nonatomic, readonly) id property;
                                   ^
error: ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

但是,如果我将类continuation的属性重新声明更改为具有weak的存储限定符,则不会生成警告或错误。 但是,(令人担忧的是)生成的代码-[MyObject setProperty:]调用objc_storeStrong而不是我预期的objc_storeWeak

据我所知,从LLVM 3.1开始,合成ivars的默认存储空间strong 我想我的问题是:为什么codegen在实现中重新声明时更喜欢标题中的声明? 其次,为什么当我重新宣布copy ,它会抱怨,但不是weakassign

我明白你的问题...

  • 您想在MyObject类成员方法中读写myproperty。
  • 但是,想要从其他班级只读我的财产。

// MyObject.h

@interface MyObject : NSObject
{
@private
    id _myproperty;
}
@property (nonatomic, copy, readonly) id myproperty;
@end

// MyObject.m

#import "MyObject.h"

@interface MyObject ()
// @property (nonatomic, copy, readwrite) id myproperty; // No needs
@end

@implementation MyObject
@synthesize myproperty = _myproperty;


- (void)aMethod
{
    _myproperty = [NSString new]; // You can read & write in this class.
}

@end

//哦

#import "MyObject.h"

void main()
{
   MyObject *o = [MyObject new];
   o.myproperty = [NSString new]; // Error!! Can't write.
   o._myproperty = [NSString new]; // Error!! Can't acsess by objective c rule.
   NSString *tmp = o.myproperty; // Success readonly. (but myproperty value is nil).
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM