CS185c
Chris Pollett
Sep. 1, 2010
@interface classname : superclassname {
int my_field;
// instance variables can be any C type or the generic id type.
}
+classMethod1; // + means class method; - means instance method
+(return_type)classMethod2;
+(return_type)classMethod3:(param1_type)parameter_varName;
-(return_type)instanceMethod1:(param1_type)param1_varName :(param2_type)param2_varName;
-(return_type)instanceMethod2WithParameter: (param1_type)param1_varName andOtherParameter:(param2_type)param2_varName;
@end
To implement the functions you use an implementation file and the syntax:
@implementation classname
+classMethod {
// implementation
}
-instanceMethod {
// implementation
}
@end
[obj method:parameter1 paramName2: parameter2]
MyObject * o = [MyObject new];
MyObject * o = [[MyObject alloc] init];
You can override the init method of your class to make a new constructor.
// Interface File
#import <objc/Object.h>
@interface MyHello : Object {
int myNumber;
}
-setNumber:(int)aNumber;
-sayHello;
@end
// implementation file
#import <stdio.h>
#import "MyHello.h"
@implementation MyHello
-setNumber:(int)aNumber { myNumber = aNumber;
}
-sayHello{
printf("Hello! %d\n", myNumber);
}
-(id) init { //self is like this in Java
self = [super init];
if (self) { myNumber = 0; }
return self;}
@end
#import "MyHello.h"
int main(void){
MyHello *hello = [MyHello new];
[hello setNumber:10];
//set the number to echo
[hello sayHello];
return 0;
}
/* To compile in gcc could type:
gcc -arch i386 -x objective-c -Wno-import main.m MyHello.m -lobjc
To get this to work on 64 bit architecture need to switch to NSObject...
You can actually build XCode projects from the command line:
/Developer/usr/bin/xcodebuild -target project
*/
-(void)dealloc
{
/* call release on instance variable; then... */
[super dealloc];
}
[myObj retain]; //increases myObj's reference count by 1. [myObj release]; // decreases myObj's reference count by 1.
//
// SecondProjectViewController.h
// SecondProject
//
// Created by Chris Pollett on 8/26/09.
// Copyright San Jose State University 2009. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface SecondProjectViewController : UIViewController {
}
@end
#import <UIKit/UIKit.h>
@interface SecondProjectViewController : UIViewController {
IBOutlet UILabel *statusText;
}
@property (retain, nonatomic) UILabel *statusText;
-(IBAction) buttonPressed:(id)sender;
@end
UILabel *tmp = myController.statusText; muController.statusText = someLabel;