2012-08-03 74 views
4

我有以下代码:Objective-C的ARC属性重复混乱

// 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 

不过,如果我更改类延续的属性重新声明,以存储限定符为weak,则不会生成警告或错误。然而,(惊人地?)生成的代码-[MyObject setProperty:]调用objc_storeStrong而不是我预期的objc_storeWeak

我知道,从LLVM 3.1开始,合成ivars的默认存储位置是strong。我想我的问题是这样的:为什么Codegen在头文件中声明我的重新声明中的声明?其次,为什么当我重新声明为copy,但不是weakassign

回答

3

我明白你的问题波纹管......

  • 你想读写的MyObject来类的成员方法myProperty的。
  • 但是,只想从其他类读取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 

// 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). 
}