Showing posts with label Objective-C. Show all posts
Showing posts with label Objective-C. Show all posts

Thursday, November 8, 2012

Objective-C Header and Class Implementation

Person.h

#import <Foundation/Foundation.h>
@interface Person:NSObject{
   NSString *name;
   int age;
}
- (NSString *)name;
- (void) setName: (NSString *) newName;

- (int)age;
- (void) setAge: (int) newAge;

//actions
- (BOOL) isAllowedToVote;
- (void castBallot;
@end

Person.m

#import "Person.h"

@implementation Person
- (int) age{
   return age;
}

- (void) setAge: (int) value{
   age = value;
}

//... and other methods

@end

Using a class
id anObject = [[SomeClass alloc] init];

- (id) init
{
   self = [super init];
   if(self){
     //initializations
   }
   return self;
}

- (Person *) createPersonWithName: (NSString *) aName{
   Person *aPerson = [[Person alloc] init];
   [aPerson setName:aName];
   [aPerson setAge:21];

   return aPerson;
}

Class Inheritance

@interface Student : Person {
   NSString *major;
}
@end

@implementation Student
// Constructor for a student
- (id) init
{
   self = [super init];
   if(self != nil){
      //set attributes
      [self setMajor:@"Undefined"];
   }
   return self;
}
@end

Objective-C Selector

id object;
SEL anAction = @selector(action:);
if([object respondsToSelector:anAction]){
   [object performSelector:anAction withObject:self];
}

Objective-C Object Messaging

[receiver message]
[receiver message:argument]
[receiver message:arg1 argument2:arg2]
int status = [receiver message];
[receiver makeGroup:group, memberOne, memberTwo, memberThree];

[rectangle draw]
[rectangle setColor:blue]
[rectangle setStrokeColor:blue andThickness:2.0]
double length = [rectangle circumference];
[NSArray arrayWithObjects:one, two, three, nil];

Java vs. Objective-C

Java
Rectangle rect = Rectangle(someWidth, someHeight);
println(rect.getHeight());
boolean inside = rect.contains(x,y);

Objective-C
Rectangle *rect = [[Rectangle alloc] initWithWidth:someWidth andHeight:someHeight];
NSLog(@"%f", [rect height]);
BOOL inside = [rect containsPointWithX:x andY:y]

Objective-C Identiy vs. Equality

// test for object identity:
BOOL identical = @"Peter" == @"Peter";     //YES
            identical = @"Peter" == @" Peter ";    //NO

// test for string equality: will return YES
NSString *aName = @"Peter";
NSMutableString *anotherName = [NSMutableString stringWithString:@"P"];

[anotherName appendString:@"eter"];

BOOL same = [aName isEqualToString:anotherName];     //YES
BOOL equal = (aName == anotherName);         //NO

// test for existence
BOOL exists = (object != nil);