tags:

views:

94

answers:

2

If I'm getting updates to data - i.e. let's say some new returned JSON for example - then what do people think is cleaner?

a) Just release any old objects, then create new ones.

or

b) Have -(id)initWithJSON:json type initializers that can 'reset' the data contained within the object to use the new data that is passed in.

The second case would mean calling the "init" methods multiple times and coding them to be careful with releasing/copying contained objects.

+3  A: 

(a) is definitely better. In general, algorithms that use immutable rather than mutable data structures are easier to write and reason about. If profiling shows that (a) is not viable, then (and only then) consider (b). If you go down that road, do your future maintainers a favor and use a resetWithJSON: or somesuch method. You can extract common code between the init and reset methods, but let your public API have both methods so that your intention is clear.

Barry Wark
+2  A: 

Barry already answered it, but let me phrase it differently:

Definitely a) is the usual approach.

You can reuse the object as you suggest in b), but when you do that, never design your class so that you would call methods named init... more than once. That is against every established custom of Objective-C.

Take NSMutableString for example. You can initialize one using

  NSMutableString* ms=[[NSMutableString alloc] initWithString:@"boo"];

and you can reset it by caling

  [ms setString:@"bar"];

but you never do

  [ms initWithString:@"boo"];

The methods named init... should only appear in conjunction with alloc, and not anywhere else.

Yuji
Thanks, got it, I was after the "established" way of doing it.
JonB