[英]Objective-C ARC property redeclaration confusion
I have the following code: 我有以下代码:
// 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
This generates the following compiler warning and error: 这会生成以下编译器警告和错误:
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
However, if I change the class continuation's property redeclaration to have a storage qualifier of weak
, no warnings or errors are generated. 但是,如果我将类continuation的属性重新声明更改为具有
weak
的存储限定符,则不会生成警告或错误。 However, (alarmingly?) the generated code for -[MyObject setProperty:]
calls objc_storeStrong
rather than my expected objc_storeWeak
. 但是,(令人担忧的是)生成的代码
-[MyObject setProperty:]
调用objc_storeStrong
而不是我预期的objc_storeWeak
。
I understand that as of LLVM 3.1, the default storage for synthesised ivars is strong
. 据我所知,从LLVM 3.1开始,合成ivars的默认存储空间
strong
。 I suppose my question is this: why is the codegen favouring the declaration in the header over my redeclaration in the implementation? 我想我的问题是:为什么codegen在实现中重新声明时更喜欢标题中的声明? Secondly, why does it complain when I redeclare as
copy
, but not weak
or assign
? 其次,为什么当我重新宣布
copy
,它会抱怨,但不是weak
或assign
?
I understand your question bellow... 我明白你的问题...
// MyObject.h // MyObject.h
@interface MyObject : NSObject
{
@private
id _myproperty;
}
@property (nonatomic, copy, readonly) id myproperty;
@end
// MyObject.m // 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
// Ohter.m //哦
#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.