Introduction to Cocoa Application
Development
Module 4: Working with Objective-C & Foundation
All Materials © 2008 Apple Inc. All Rights Reserved.
Objective-C Types
Dynamic vs. Static Typing
■ Statically typed object
Person *anObject
■ Dynamically typed object
id anObject
■ Objective-C provides compile time type checking
- Use of id defeats compile time checking
■ id used for Dynamic Binding
- Objective-C Runtime picks the actual method to use for all
objects at runtime
Runtime Method Selection
Rectangle
draw
Circle
draw
- (void)drawRectangle:(Rectangle*)rect
{
[rect draw];
}
- (void)drawCircle:(Circle*)circle
{
[circle draw];
}
- (void)drawShape:(id)shape
{
[shape draw];
}
Runtime Method Selection
Rectangle
draw
Circle
draw
- (void)drawRectangle:(Rectangle*)rect
{
// Compiler flags this as a Warning
[rect drawed];
}
- (void)drawShape:(id)shape
{
// DANGER: No Compiler Warning!
[shape drawed];
}
Null Object Pointer
■ Testing for nil
	 Person *person;
	 if (person == nil)
	 	
return;
■ Use in assignments and as arguments (if expected)
	 person = nil;
	 [button setTarget:nil];
■ Sending a message to nil?
	 person = nil;
	 [person payRaise:100];
BOOL typedef
■ BOOL is not a native C type
■ Objective-C introduces a typedef for BOOL
BOOL isEligibleToVote = NO;
■ Macros included for common operations
if (isEligibleToVote == YES)
if (isEligibleToVote)
if (!isEligibleToVote)
if (isEligibleToVote != YES)
isEligibleToVote = YES;
isEligibleToVote = 1;
Working with Classes
Class Introspection
■ Query an object about its class
Class myClass = [anObject class];
NSLog (@“My class is %@”, [anObject className]);
■ Test for general class membership (including
subclasses)
if ([anObject isKindOfClass:[NSControl class]])
■ Test for specific class membership (excluding
subclasses)
if ([anObject isMemberOfClass:[NSString class]])
Class Methods
■ Instance Method - operates on a specific object
■ Class Method - global and has no specific data
associated with them
■ ‘-’ denotes an instance method
- (void)setRate:(int)rate;