简体   繁体   中英

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. However, (alarmingly?) the generated code for -[MyObject setProperty:] calls objc_storeStrong rather than my expected objc_storeWeak .

I understand that as of LLVM 3.1, the default storage for synthesised ivars is strong . I suppose my question is this: why is the codegen favouring the declaration in the header over my redeclaration in the implementation? Secondly, why does it complain when I redeclare as copy , but not weak or assign ?

I understand your question bellow...

  • You want to readwrite myproperty in MyObject class member method.
  • But, want to readonly myproperty from other class.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM