Wednesday, April 17, 2013

Objective C's C# auto-implemented properties

Missing C#'s auto-implemented properties?

For the uninitiated, here's what auto-implemented properties in C# looks like:

public class ThePerson 
{
    public int HatedNumber {get; set;}
}


That syntax spares the developer from incessant creations of backing field for property and explicitly coding the property's getter and setter
public class The Person 
{
 int _hatedNumber;
 public int HatedNumber
 {
    get 
    { 
        return _hatedNumber;
    }
    set 
    { 
        _hatedNumber = hatedNumber;
    }
 }


Writing that things over and over easily gets old, hence the creation of auto-implemented properties in the language. Auto-implemented properties creates codes for you behind-the-scenes, rather than the you writing the repetitive and boring stuff



Objective-C has analogous mechanism to that C#'s auto-implemented property

ThePerson.h:
#import *<Cocoa/Cocoa.h>

@interface ThePerson : NSObject {
}

    @property int hatedNumber;

@end

ThePerson.m:
#import "ThePerson.h"

@implementation ThePerson

    @synthesize hatedNumber;

@end


It behaves exactly the same as in C#, i.e. you don't have to write explicit setter and getter code for your property. And you can still use the property as if dot notation was not invented, i.e. you can still invoke its setter explicitly [objectInstanceHere setHatedNumber]

#include <CoreFoundation/CoreFoundation.h>


#include "ThePerson.h"

int main(int argc, const char * argv[])
{

    // insert code here...
    
    ThePerson* p = [ThePerson new];
    
    ThePerson* q = [ThePerson new];
    
    ThePerson *x;

    
    x = p;
    [x setHatedNumber:4]; // classic way
    
    x = q;
    x.hatedNumber = 13; // modern way
    
    
    
    printf("%d\n", [p hatedNumber]); // classic way
    printf("%d\n", p.hatedNumber); // modern way
    
    printf("%d\n", [q hatedNumber]); // classic way
    printf("%d\n", q.hatedNumber); // modern way
    


    return 0;
}





Happy Computing! ツ


UPDATE

On Xcode 4.4, synthesize keyword is not needed anymore when creating automatic properties, and by default it automatically creates a backing field for your property, which name is prefixed by an underscore followed by the property name. I would prefer it not exposing any backing field, just like with the automatic property in C#

No comments:

Post a Comment