iphone - Best practices for mutable collections as properties -



iphone - Best practices for mutable collections as properties -

i planning utilize nsmutabledictionary property storing game info (such score, settings, etc...).

@property (nonatomic, copy) nsmutabledictionary *gamedata;

in researching why there no "mutablecopy" alternative properties found this discussion, accepted reply states:

the right way not create mutable array property

what best way handle mutable collections properties in modern objective-c?

it quite seldom pattern class expose mutable property collection object seems break encapsulation.

nevertheless there are occasions when might create sense: could, illustration homecoming kvo proxy internally managed collection (using kvc's mutablearrayvalueforkey:).

in these cases not matter whether or not declare getter property or plain method. in case of properties should not copy property, though.

to create little clearer here's example. have class declares single public getter:

@interface foo : nsobject @property (strong, readonly) nsmutablearray *publicbars; @end

the implementation manages encapsulated, private mutable array named _bars:

@implementation foo { nsmutablearray *_bars; }

the elements of array exposed kvc to-many accessors:

- (nsuinteger)countofbars { homecoming [_bars count]; } - (id)objectinbarsatindex:(nsuinteger)idx { homecoming _bars[idx]; } - (void)insertobject:(id)object inbarsatindex:(nsuinteger)idx { if (_bars == nil) _bars = [nsmutablearray array]; [_bars insertobject:object atindex:idx]; } - (void)removeobjectfrombarsatindex:(nsuinteger)idx { [_bars removeobjectatindex:idx]; }

here's fancy part: implementing public property returning a kvc proxy reflects , mutates internal state without exposing internal ivars. changes internal array using public accessors defined above.

- (nsmutablearray *)publicbars { homecoming [self mutablearrayvalueforkey:@"bars"]; } @end

we can utilize proxy alter internal collection:

foo *foo = [[foo alloc] init]; nsmutablearray *bars = foo.publicbars; [bars addobject:@1]; [bars addobject:@2]; [bars removeobjectatindex:0]; // internal _bars array @[ @2 ].

there actual examples of , similar patterns in cocoa. illustration there -[nstextview textstorage] returns internal backing store (an object derived nsmutableattributedstring). though not collection object mutable object passes mutations host object, text view.

iphone ios objective-c

Comments

Popular posts from this blog

javascript - mongodb won't find my schema method in nested container -

How do you set up a perforce server to work over the internet? -

ios - Lagging ScrollView with UIWebview inside -