4

我有以下代码:

// 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. 我想我的问题是这样的:为什么代码生成器偏爱标题中的声明而不是我在实现中的重新声明?其次,为什么当我重新声明为时它会抱怨copy,而不是weakor assign

4

1 回答 1

3

我明白你下面的问题...

  • 您想在 MyObject 类成员方法中读写 myproperty。
  • 但是,想从其他类中读取 myproperty。

// MyObject.h

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

// 我的对象.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).
}
于 2012-08-03T00:37:18.760 回答