Defending your Datamodel classes

November 28th, 2010

On a project recently I had to develop some model classes that would be populated upon creation from a web service. A requirement was that once the model object where created they should not be altered. As I wasn't the sole coder on this project I decided to defend these objects and ensure that their properties were indeed read-only.

Photo of a Rottweiler protecting a puppy

Objective-C doesn't lend itself to strong encapsulation due its dynamic nature so I had to think outside the box. I decided on using private instance variables with read-only properties however to ensure that I didn't attempt to use the properties by mistake when I meant to use the instance variable I gave my instance variables different names and linked them with the their properties in the .m file.


@interface Person : NSObject {
	NSString *_name;
	NSDate *_dob;
	NSString *_telephone;
	NSString *_addressLine1;
	NSString *_addressLine2;
	NSString *_postCode;
	NSString *_email;

@property(nonatomic, readonly) NSString *name;
@property(nonatomic, readonly) NSDate *dob;
@property(nonatomic, readonly) NSString *telephone;
@property(nonatomic, readonly) NSString *addressLine1;
@property(nonatomic, readonly) NSString *addressLine2;
@property(nonatomic, readonly) NSString *postCode;
@property(nonatomic, readonly) NSString *email;



@implementation Person

@synthesize name = _name;
@synthesize email = _email;
@synthesize dob =_dob;
@synthesize telephone = _telephone;
@synthesize addressLine1 = _addressLine1;
@synthesize addressLine2 = _addressLine2;
@synthesize postCode = _postCode;

-(id)initWithDict:(NSDictionary *)dict{
    self = [super init];
    _name = [[dict objectForKey:@"name"] retain];
    _dob = [[dict objectForKey:@"dob"] retain];
    _telephone = [[dict objectForKey:@"tel"] retain];
    _email = [[dict objectForKey:@"email"] retain];
    _addressLine1 = [[dict objectForKey:@"addLine1"] retain];
    _addressLine2 = [[dict objectForKey:@"addLine2"] retain];
    _postCode = [[dict objectForKey:@"pcode"] retain];
    return self;


What do you think? Let me know by getting in touch on Twitter - @wibosco