Objective C
Introduction
Objective-C is a strict superset of C. It adds in the concept of messaging:
[myArray insertObject:anObject atIndex:0];
File management
.h
is for header files, containing class, type, function, and constant declarations..m
is for source files, containing implementations.- Use
#import
to access declarations from other files.
Memory management
If you create a variable of a non-builtin-type (not int or float), then you need to release it when you're done with it:
[tempName release];
Call this within scope for a temporary variable, or in the class's dealloc
method for an instance variable.
Classes
Interface declaration in MyClass.h:
#import "MySuperClass.h"
@interface MyClass : MySuperClass {
// instance variables
}
+classMethod1; // void return type
+(return_type)classMethod2; // takes no parameter
+(return_type)classMethod3:(param_type)paramName;
-(return_type)instanceMethod:(param_type)param1 :(param_type)param2;
-(return_type)instanceMethodWithNamedParameter:(param_type)param1 namedParameter:(param_type)param2;
@end
Another interface declaration in MyOtherClass.h:
@interface MyOtherClass : NSObject
{
int count; // strongly typed
id data; // weakly typed - allows assignment of an arbitrary object
NSString* name; // strongly typed
}
- (id)initWithString:(NSString*)aName; // instance method
+ (MyOtherClass)createWithString:(NSString*)aName; // class method
@end
An implementation in MyOtherClass.m:
@implementation MyOtherClass
- (id)initWithString:(NSString *)aName
{
if (self = [super init]) {
name = [aName copy];
}
return self;
}
+ (MyOtherClass *)createWithString: (NSString *)aName
{
return [[[self alloc] initWithString:aName] autorelease];
}
@end
Class properties with getters and setters
In the .h file:
@property BOOL flag;
@property (copy) NSString *nameObject; // Copy the object during assignment.
@property (readonly) UIView *rootView; // Declare only a getter method.
Generate the appropriate getters and setters in the .m file with synthesize:
@synthesize flag, nameObject, rootView;
Strings
String literals must be preceded by an @ sign:
NSString *myString = @"My String\n";
NSString *anotherString = [NSString stringWithFormat:@"%d %s", 1, @"String"];