Twitter Stream

Flickr Photos

Missing Objective-C 2.0 Feature(s)

This post was inspired by a recent twitter that I thought I might elaborate on a bit more. One of the nice new features of Objective-C 2.0 is dot-syntax for read/write proprerties. For example:

Person *person = [[Person alloc] init];
person.mobileNumber = @"1-555-123-1234";

This is uber nifty, and can save you a load of time and redundant code. However it’s often the case that I want to hide access to certain private member variables, but still expose accessors/mutators to attributes on those private variables. Let’s say mobileNumber is actually an accessor/mutator on a sub-object, let’s call it PhoneBook. Under the hood, this is implemented like so:

@interface Person {
    PhoneBook *phoneBook;
}

@property (nonatomic, rertain) NSString *mobileNumber;
@end

@implementation Person
- (void)setMobileNumber:(NSString *)number {
    phoneBook.mobileNumber = number;
}

- (NSString *)mobileNumber {
    return phoneBook.mobileNumber;
}
@end

This seems far from ideal, when really I just want to pass through the implementation of this accessor/mutator to one of my instance variables. A more clean and hypothetical implementation could look like this:

@interface Person {
    PhoneBook *phoneBook;
}

@property (nonatomic, retain) NSString *mobileNumber;
@end

@implementation Person
@synthesize mobileNumber=phoneNumber.mobileNumber;
@end


2 Responses to “Missing Objective-C 2.0 Feature(s)”


  1. Gravatar James F Says:

    Ohh. And imagine the possibilities if phoneBook.mobileNumber was mapped to person.mobileNumber.

    Alternatively, you could define a protocol for the properties in PhoneBook that you want public and then make an - idphoneBook getter for Person. Then people could use person.phoneBook.mobileNumber = “1-555-123-4567” but still not have access to your private stuff.

  2. Gravatar Jeff Barbose Says:

    Actually, the dot operator is a shortcut and attempts to use canonical forms of getters/setters before it goes directly to the variable.

    You can choose the privacy level of the data, as well.

Leave a Reply