Objective-C ARC属性重声明混淆

4

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

这将生成以下编译器警告和错误:
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开始,合成的实例变量默认的存储方式是strong。我的问题是:为什么代码生成器更喜欢头文件中的声明而不是我在实现中重新声明的呢?其次,为什么当我重新声明为copy时会报错,但没有使用weakassign时却不会报错?
1个回答

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接