本文介绍了如何在头文件(.h)中创建一个不可变的readonly属性,在implementaion(.m)中有一个可变的readwrite属性,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,它包含一个字典 JSONData 。从头文件和其他访问它的类,我希望这个属性只能是只读的和不可变的。

I have an object that holds a dictionary JSONData. From the header file, and to the other classes that'll access it, I want this property to only be read-only and immutable.

@interface MyObject : NSObject

@property (readonly, strong, nonatomic) NSDictionary *JSONData;

@end

但是,我需要 readwrite 和可变参数,如下所示,但不起作用:

However, I need it to be readwrite and mutable from the implementation file, like this, but this doesn't work:

@interface MyObject ()

@property (readwrite, strong, nonatomic) NSMutableDictionary *JSONData;

@end

@implementation MyObject

// Do read/write stuff here.

@end

有什么我可以做的,我要去的抽象?我看了其他问题,虽然我已经知道如何从 .h 和<$ c中创建属性 readonly $ c> readwrite 从 .m ,我找不到任何关于可变性的差异。

Is there anything I can do to enforce the kind of abstraction I'm going for? I looked at the other questions and while I already know how to make a property readonly from .h and readwrite from .m, I can't find anything about the difference in mutability.

推荐答案

您的实现中需要一个单独的私有可变变量。您可以覆盖getter以返回不可变对象。

You need a separate private mutable variable in your implementation. You can override the getter to return an immutable object.

@interface MyObject () {
  NSMutableDictionary *_mutableJSONData;
}
@end

@implementation MyObject 

// ...

-(NSDictionary *)JSONData {
   return [NSDictionary dictionaryWithDictionary:_mutableJSONData];
}

// ...
@end

不需要实现setter,因为它是 readonly

No need to implement the setter, as it is readonly.

这篇关于如何在头文件(.h)中创建一个不可变的readonly属性,在implementaion(.m)中有一个可变的readwrite属性,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:31