簡體   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