Objective-C NSCoding和只读

Nin*_*jaG -1 objective-c

Objective C只读

我想将我的NSCoding属性更改为只读.例如,让我们在Person上设置lastName属性的readonly属性:

Person.h
@interface Person : NSObject
@property NSString *firstName;
@property (readonly) NSString *lastName;
@end
Run Code Online (Sandbox Code Playgroud)

分配给只读属性

好的,所以外部代码不能设置属性值,但是当我在@property声明之后通过包含(readonly)标记带有readonly属性的lastName属性时.但我仍然收到这样的错误:

Person.m
#import "Person.h"

@implementation Person

- (void) changeLastName:(NSString *)newLastName;
{
  self.lastName = newLastName;
}
@end
Run Code Online (Sandbox Code Playgroud)

分配给只读属性

这里发生了什么?有人能告诉我为什么它不起作用.谢谢.

Río*_*ire 5

你需要在类中重新声明它作为readwrite

// Person.m
#import "Person.h"

@interface Person()
@property (readwrite) NSString *lastName;
@end

@implementation Person

-(void)changeLastName:(NSString *)newLastName;
{
  self.lastName = newLastName;
}

@end
Run Code Online (Sandbox Code Playgroud)