Tuesday, April 16, 2013

Objective C's class and property

main.m

#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 setFavoriteNumber:7]; // classic way
    
    x = q;
    x.favoriteNumber = 6; // modern. neater syntax, lesser friction. calls the method setFavoriteNumber
    
    
  
    printf("%d\n", [p favoriteNumber]); // classic way
    printf("%d\n", p.favoriteNumber); // modern way
    
    printf("%d\n", [q favoriteNumber]); // classic way
    printf("%d\n", q.favoriteNumber); // modern way
    

    return 0;
}



The class mechanism for Objective C uses the interface keyword. Then we put the backing field inside the curly bracket. And all the method signature after the curly bracket.

Person.h
#import <Cocoa/Cocoa.h>

@interface ThePerson : NSObject {
    int _favoriteNumber;
}


-(int) favoriteNumber; 
-(void) setFavoriteNumber: (int) input;



@end


Person.m
#import "ThePerson.h"

@implementation ThePerson


-(int)favoriteNumber {
    return _favoriteNumber;
}

-(void) setFavoriteNumber:(int)input {
    printf("Set is Called\n");
    _favoriteNumber = input;
}

@end

No comments:

Post a Comment