user1107173 user1107173 - 2 months ago 9
Objective-C Question

Objective-C: Mutating a property in implementation file

PeopleClass.h

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


I would like to make the
people
property above mutable (
NSMutableDictionary
) only in .m file. So when I mutate
people
dictionary, the changes are reflected in the interfaces
NSDictionary


I have tried making an iVar like below, but that didn't work.

PeopleClass.m

@interface PeopleClass ()
{
NSMutableDictionary *people;
}


What's the best way to accomplish this?

Answer

To do what you want you need to provide your own instance variable and your own setter and getter methods. Below is the basic setup:

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];
}

The use of copy in the getter method is optional. It depends on how you want the result to be handled.

It would probably also make sense to change the property to be copy instead of strong since the implementation of the setter and getter really honor copy and not just strong.