2016-09-29 55 views
0
PeopleClass.h 

@interface PeopleClass : NSObject 
@property (strong, nonatomic) NSDictionary *people; 
@end 

我想作上述可变(NSMutableDictionary)仅在.m文件的people属性。所以,当我突变people字典,变化反映在接口NSDictionary的Objective-C:在实现文件中变异的特性

我已经尝试制作像下面的iVar,但没有奏效。

PeopleClass.m 

@interface PeopleClass() 
{ 
    NSMutableDictionary *people; 
} 

完成此操作的最佳方法是什么?

回答

3

要做你想要的,你需要提供你自己的实例变量和你自己的setter和getter方法。以下是基本设置:

PeopleClass.h

@interface PeopleClass : NSObject 
@property (strong, nonatomic) NSDictionary *people; 
@end 

PeopleClass.m

@implementation PeopleClass { 
    NSMutableDictionary *_people; 
} 

- (NSDictionary *)people { 
    return [_people copy]; // or just return _people 
} 

- (void)setPeople:(NSDictionary *)people { 
    _people = [people mutableCopy]; 
} 

在getter方法中使用的copy是可选的。这取决于您希望如何处理结果。

它很可能也是有道理改变属性为copy而不是strong因为二传手的实施和getter真正兑现copy并不仅仅是strong

1

你真的不想将可变字典作为客户端的不可变引用返回。首先,如果稍后进行变异,那么消耗该引用的代码很可能会因为它不能变异的假设而写入而破坏。其次,所述代码的某些客户端可能会有一个错误,导致内容发生变化,从而导致代码中断(这发生在Cocoa中)。

相反:

@interface PeopleClass : NSObject 
@property (readonly, strong, nonatomic) NSDictionary *people; 
@end 

在您的m:

@interface PeopleClass() 
@property (strong, nonatomic) NSMutableDictionary *mutablePeople; 

- ... init ... 
{ 
    .... 
    _mutablePeople = [[NSMutableDictionary alloc] init]; 
    .... 
} 

- (NSDictionary *) people 
{ 
    return [_mutablePeople copy]; 
} 

如果复制是真的一个性能问题(由仪表&分析确定的),那么你就可以保持副本各地并在后备存储发生变化时使其无效/取代。