Introduction to Cocoa Application
Development
Module 5: Categories, Protocols and Memory Management
All Materials © 2008 Apple Inc. All Rights Reserved.
Objective-C Categories
Objective-C Categories
■ Ability to add methods to any Objective-C class
- Common alternative to subclassing
- Source to original class not needed
- Cannot add instance variables
■ Useful to Extend Framework Classes
- Foundation, AppKit
■ Reference other methods in the class using self
Category Example
■ Return all objects in an NSArray in the reverse
order
#import <Cocoa/NSArray.h>
@interface NSArray (ReversedObjectsArray)
- (NSArray*)reversedObjectsArray;
@end
Category Example (ctd.)
@implementation NSArray (ReversedObjectsArray)
- (NSArray*)reversedObjectsArray
{
NSMutableArray *outArray = [NSMutableArray array];
NSEnumerator *objectEnumerator = [self reverseObjectEnumerator];
id objectInArray = nil;
while (objectInArray = [objectEnumerator nextObject])
{
[outArray addObject:objectInArray];
}
return outArray;
}
@end
Using a Category
■ At runtime, the new methods are part of the class
{
NSArray *weekDays = [NSArray arrayWithObjects:@“Monday”,
@“Tuesday”, @“Wednesday”, @“Thursday”, @“Friday”,
nil];
NSArray *reversedWeekDays = [weekDays reversedObjectsArray];
}
Protocols
Protocols
■ Objective-C supports single inheritance
■ Sometimes desired functionality cuts across class
boundaries
■ Protocols define only an interface, no
implementation
■ A class ‘conforms’ to a protocol by implementing
all of its methods
■ Very similar to Java interfaces
Protocols - interface across classes
#import <Cocoa/Cocoa.h>
@protocol Drawing
// Only method declarations - no implementation
- (void)draw;
- (NSSize)maxSize;
- (NSSize)minSize;
@end
Classes declare conformance
@interface Shape : NSObject <Drawing> {
int _xPosition, _yPosition;
}
- (void)draw;
- (NSSize)maxSize;
- (NSSize)minSize;
@end
Working with protocols
■ Use angle brackets to declare conformance of a
class
@interface Shape : NSObject <Drawing>
■ List multiple protocols separated by comm