Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary vs. custom object

The question is quite simple: When I create a new API or Service Class should I create a custom class for the objects that are being passed around or should I just stick to an NSDictionary which simply holds the data in a key-value-style format.

Obviously there are pros and cons but where do you guys think is the threshold of using one over the other?

NSDictionary:

+ No dependencies
+ Very Flexible
+ Commonly used
+ Build-in support for NSCoding
- Structure not defined -> Runtime errors

A custom Object:

+ Structure defined
+ Property-style accessors: myObject.someProperty - Can result in a rel. big number of classes for nested objects

Update: Included remarks from jbat100

like image 481
Besi Avatar asked Nov 21 '11 09:11

Besi


People also ask

What is NSDictionary?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.

Does NSDictionary retain objects?

An NSDictionary will retain it's objects, and copy it's keys.


2 Answers

I usually have a set of domain models, which fit better with the MVC approach of iPhone development. Having specific objects also enables you to enforce type-safety a lot easier and also reduces complexity in the long run. If you have NSDictionaries containing NSArrays and more NSDictionaries etc etc to represent your object graph, it can very quickly become unmanageable.

like image 59
Simon Lee Avatar answered Oct 08 '22 20:10

Simon Lee


It really depends how much you expect your data model to change. Dealing with changes once you have a custom class based data model can be tricky especially when you have archives (NSCoding stuff) with different versions of the model (in already shipped versions of your app), you must be very careful to ensure backwards compatibility and avoid nasty run time surprises. In that respect NSDictionary based models are, as you say more flexible. However they do not allow all the customized checks and behaviour that custom classes do. Also custom classes make the data model more explicit for coders unfamiliar with the code, from my experience, developers often get sloppy (especially when inexperienced) when dealing with NSDictionary based models which can quickly result in an incomprehensible mess, so if you go down that route, document well and be disciplined!

like image 35
jbat100 Avatar answered Oct 08 '22 20:10

jbat100