Enumerating, Categories,
 Protocols and Delegates
      TN Valley Apple Developers
          Saturday CodeJam

         De...
Collections
At our last session, we were introduced to
a number of Objective-C classes that are
used to create what is cal...
Control Structures
We were also introduced to a number of
looping type “control structures” that are
used to control the l...
NSEnumerator
Objective-C has a class, NSEnumerator,
that provides a more idiomatic way to
iterate through an Objective-C c...
Example
graphicsObject = [GraphicsObject alloc] init];
...
NSArray *displayList = …[an array of
graphicsObjects to draw];
...
The Truth Value
The expression being tested, graphicsObject =
[NSEnumerator nextObject], will evaluate to true
as long as ...
Modifying Enumerated
           Objects
Not safe: results may be unpredictable
•   Create a new collection that contains t...
Fast Enumeration with for/in


Objective-C 2.0 added a new control
structure specifically for enumerating
over collections...
Structure
for (type loopVariable in expression) {
     //Code block to execute
     ...
 }
 expression must be an object, ...
Advantages of Fast Enumeration
     over NSEnumeration
Code is cleaner
Executes faster: behind the scenes, fast
enumeratio...
Categories
Categories let you “extend the functionality” of
existing classes by adding methods without
subclassing, and wi...
Why not Subclass?
Certain classes in Cocoa are actually “class
clusters” – the publicly visible class is an
abstract class...
Why not Subclass (cont)?
Subclassing a class implemented as a
cluster is an advanced programming
technique that is much mo...
Overriding Methods
Using a Category to add behavior to a class
adds that behavior for all instances of that
class within t...
What about Subclassing?

Categories can be used to add or override
methods, but cannot change an object’s
instance variabl...
Example: CamelCase
You have an application that will be making
extensive use of CamelCase in modifying
NSString objects
Th...
CamelCase Interface

#import <Foundation/Foundation.h>
@interface NSString (CamelCase)
- (NSString *)cameCaseString;
@end
CamelCase Implementation
#import “NSString+CamelCase.h”
@implementation NSString (CamelCase)
- (NSString *)camelCaseString...
Using New camelCaseString
         Method
NSString *string = @”Now is the time
for action”;
NSLog(@”%@”, string);
string =...
Protocols

A Protocol is a defined set of methods
that a class can choose to implement
Protocols can have methods that are...
Protocols
Using a Protocol on a class creates a
“contract” of sorts, where you are in
effect agreeing to implement a certa...
Cocoa and Protocols
Cocoa, especially libraries written for
iOS, make extensive use of Protocols
  Every iOS application h...
Declaring a Protocol

Protocol names are enclosed in <angle
brackets>
Protocols are declared by declaring its
methods betw...
Declaring a Protocol: an example
  @protocol DrawableItem
  - (void) drawItem;
  - (NSRect) boundingBox;
  - (NSColor *)co...
Declaring a Protocol
The protocol declaration goes into a
header file, which is usually named
after the protocol
There is ...
Optional vs. Required Methods



  Optional and required methods are
  segmented off using the @optional and
  @required c...
For Example
@protocol DrawableItem
@required
- (void) drawItem;
- (NSRect) boundingBox;
- (NSColor *)color;
- (void)setCol...
Adopting a Protocol
A class adopts a protocol by implementing
all of the protocol’s required methods and
any or none of it...
Adopting a Protocol
@interface AcmeUniversalBolt : AcmeComponent
<DrawableItem>
- (void) drawItem { //code to draw }
- (NS...
Adopting a Protocol
 Classes can adopt more than one protocol
        Protocols are listed between a single set of
       ...
Delegates: A special type of
         Protocol
Delegation is a recurring design pattern
in iOS
In Cocoa programming, you s...
Callbacks
A callback is a function that gets
triggered when a certain event occurs; in
iOS this is frequently in response ...
Delegate in Code
Every object that listens for messages
from a delegate object contains an
instance variable that points t...
Naming Convention

By convention, every protocol designed
as a delegate protocol is named as
follows:
The name of the clas...
Documentation
Every delegate protocol has a corresponding
documentation page in Apple’s developer
documentation that descr...
Example:
   UIApplicationDelegate
Every Cocoa Touch application (which is to
say every iOS application) implements an
Appl...
Implementation


It’s extremely important to make sure
you match the name and type of
arguments exactly as they are declar...
Steps for Implementing a
 Delegate Protocol in Code
Declare a class to conform to the object’s
delegate protocol
Implement...
In Preparation for 2011
Upgrade to XCode 3.2.5 / iOS 4.2
Register as an Apple Developer
Plan to upgrade to an iOS Develope...
May you and yours have a wonderful
        Christmas holiday!
See you
in 2011!
           42
Enumerating categories protocols delegates
Upcoming SlideShare
Loading in …5
×

Enumerating categories protocols delegates

1,827 views
1,677 views

Published on

Enumerating, Categories, Protocols and Delegates

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,827
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
35
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Enumerating categories protocols delegates

  1. 1. Enumerating, Categories, Protocols and Delegates TN Valley Apple Developers Saturday CodeJam December 18, 2010
  2. 2. Collections At our last session, we were introduced to a number of Objective-C classes that are used to create what is called a “collection”, which is an object that contains other objects on which it performs various operations Collections are: NSArray, NSDictionary, NSSet, NSData, etc.
  3. 3. Control Structures We were also introduced to a number of looping type “control structures” that are used to control the logical flow of program execution, including the “while” loop Refresher: the while loop tests a condition and continues to loop through a block of code as long as that condition is true This “looping” process is called iteration
  4. 4. NSEnumerator Objective-C has a class, NSEnumerator, that provides a more idiomatic way to iterate through an Objective-C collection NSEnumerator takes a collection and doles out its objects (using the method nextObject), one at a time, until all of the objects have been dispensed
  5. 5. Example graphicsObject = [GraphicsObject alloc] init]; ... NSArray *displayList = …[an array of graphicsObjects to draw]; NSEnumerator *myEnumerator = [displayList objectEnumerator]; while (graphicsObject = [myEnumerator nextObject] ) { [graphicsObject draw]; }
  6. 6. The Truth Value The expression being tested, graphicsObject = [NSEnumerator nextObject], will evaluate to true as long as graphicsObject contains an actual object. when all of the objects in the collection have been handed out, graphicsObject = [NSEnumerator nextObject] will be false and the loop will end. If you want to iterate the collection again, you need to refresh the NSEnumerator object: myEnumerator = displayList [object Enumerator];
  7. 7. Modifying Enumerated Objects Not safe: results may be unpredictable • Create a new collection that contains the original collection’s objects and enumerate the new collection while modifying the original • Enumerate the collection and create a list of required changes; apply those changes when enumeration is complete
  8. 8. Fast Enumeration with for/in Objective-C 2.0 added a new control structure specifically for enumerating over collections: the for/in loop Runs faster than traditional loops based on NSEnumerator, with less overhead
  9. 9. Structure for (type loopVariable in expression) { //Code block to execute ... } expression must be an object, usually a collection, that conforms to the NSFastEnumeration protocol (NSArray, NSDictionary, NSSet, NSManagedObjectModel, etc.) The file naming convention for categories is ClassName +CategoryName.
  10. 10. Advantages of Fast Enumeration over NSEnumeration Code is cleaner Executes faster: behind the scenes, fast enumeration asks for groups of objects, which eliminates many message dispatches Safe: collections subject to fast enumeration are protected from modification
  11. 11. Categories Categories let you “extend the functionality” of existing classes by adding methods without subclassing, and without requiring access to the class source code Structure: @interface BaseClass (Category) - (method to be added) @end
  12. 12. Why not Subclass? Certain classes in Cocoa are actually “class clusters” – the publicly visible class is an abstract class, with a number of private subclasses that implement the interface defined by the public abstract class Creating an instance using the public class actually returns an instance of one of the private classes, depending on the init method used
  13. 13. Why not Subclass (cont)? Subclassing a class implemented as a cluster is an advanced programming technique that is much more complicated than subclassing a simple class If you are using a pre-compiled third- party library, you may not have access to source code data (header files) to allow you to subclass effectively
  14. 14. Overriding Methods Using a Category to add behavior to a class adds that behavior for all instances of that class within that project You can override an existing method, which may result in unintended consequences Overriding an existing method using a category leaves no way to call the original method
  15. 15. What about Subclassing? Categories can be used to add or override methods, but cannot change an object’s instance variables If you want to limit the behavior to a subset of the class, you will need to create a subclass
  16. 16. Example: CamelCase You have an application that will be making extensive use of CamelCase in modifying NSString objects The NSString class, which is actually a class cluster, has no existing method to apply CamelCase to a string object You create a category that contains a method that applies CamelCase to an NSString object, and implement it on the NSString class
  17. 17. CamelCase Interface #import <Foundation/Foundation.h> @interface NSString (CamelCase) - (NSString *)cameCaseString; @end
  18. 18. CamelCase Implementation #import “NSString+CamelCase.h” @implementation NSString (CamelCase) - (NSString *)camelCaseString { //code for converting string to CamelCase format } @end
  19. 19. Using New camelCaseString Method NSString *string = @”Now is the time for action”; NSLog(@”%@”, string); string = [string camelCaseString]; NSLog(@”%@”, string); camelCaseString gets called just like any other NSString method
  20. 20. Protocols A Protocol is a defined set of methods that a class can choose to implement Protocols can have methods that are required or optional. Required methods must be implemented by the adopting class
  21. 21. Protocols Using a Protocol on a class creates a “contract” of sorts, where you are in effect agreeing to implement a certain set of methods on the class adopting the protocol Protocols can be used to create consistency in interfacing different objects with a similar subset of behaviors
  22. 22. Cocoa and Protocols Cocoa, especially libraries written for iOS, make extensive use of Protocols Every iOS application has a class that implements the UIApplicationDelegate protocol, which is the protocol used for any application that utilizes UIKit (the user interface library)
  23. 23. Declaring a Protocol Protocol names are enclosed in <angle brackets> Protocols are declared by declaring its methods between the @protocol and @end compiler directives
  24. 24. Declaring a Protocol: an example @protocol DrawableItem - (void) drawItem; - (NSRect) boundingBox; - (NSColor *)color; - (void)setColor:(NSColor*)color; @end
  25. 25. Declaring a Protocol The protocol declaration goes into a header file, which is usually named after the protocol There is no implementation file Each class adoption the protocol will provide its own implementation of any required methods for the protocol
  26. 26. Optional vs. Required Methods Optional and required methods are segmented off using the @optional and @required compiler directives
  27. 27. For Example @protocol DrawableItem @required - (void) drawItem; - (NSRect) boundingBox; - (NSColor *)color; - (void)setColor:(NSColor*)color; @optional - (NSString *) labelText; @end
  28. 28. Adopting a Protocol A class adopts a protocol by implementing all of the protocol’s required methods and any or none of its optional methods, either specifically or through inheritance The compiler is informed that a class is adopting a protocol by including the protocol name in <angle brackets> on the interface line
  29. 29. Adopting a Protocol @interface AcmeUniversalBolt : AcmeComponent <DrawableItem> - (void) drawItem { //code to draw } - (NSRect) boundingBox { //code defining boundingBox } - (NSColor *) color ( //code retrieving color } - (void) setColor: (NSColor *) color { // code to set color } @end
  30. 30. Adopting a Protocol Classes can adopt more than one protocol Protocols are listed between a single set of <angle brackets>, separated by commas Variables can also be declared of a type of object conforming to a protocol: id <DrawableItem> currentGraphic; If you try to assign an object not conforming to DrawableItem to currentGraphic, the compiler will complain
  31. 31. Delegates: A special type of Protocol Delegation is a recurring design pattern in iOS In Cocoa programming, you spend alot of time sending messages to objects Sometimes you want an object to send messages to you; this is called a callback
  32. 32. Callbacks A callback is a function that gets triggered when a certain event occurs; in iOS this is frequently in response to some sort of user input. In Cocoa Touch, callbacks are implemented using a technique called delegation
  33. 33. Delegate in Code Every object that listens for messages from a delegate object contains an instance variable that points to the delegate object The delegate object, in turn, implements the delegate protocol for the listening object, and sends messages accordingly
  34. 34. Naming Convention By convention, every protocol designed as a delegate protocol is named as follows: The name of the class doing the delegation suffixed with “Delegate”
  35. 35. Documentation Every delegate protocol has a corresponding documentation page in Apple’s developer documentation that describe the required and optional methods associated with that protocol In addition, the templates in Xcode that generate your skeleton projects will many times provide method declarations for the required methods, and some provide declarations for optional methods that are commented out
  36. 36. Example: UIApplicationDelegate Every Cocoa Touch application (which is to say every iOS application) implements an Application Delegate, whose responsibility is to send messages from the user interface to the application via the UIApplication object Each Application delegate is by default named ProjectAppDelegate; its interface and implementation files can be found in the your project’s “Classes” folder in Xcode
  37. 37. Implementation It’s extremely important to make sure you match the name and type of arguments exactly as they are declared in the protocol
  38. 38. Steps for Implementing a Delegate Protocol in Code Declare a class to conform to the object’s delegate protocol Implement the necessary delegate methods (required ones and any optional ones you are using) Set the delegate pointer of the object to point to the instance of your class adopting the delegate protocol
  39. 39. In Preparation for 2011 Upgrade to XCode 3.2.5 / iOS 4.2 Register as an Apple Developer Plan to upgrade to an iOS Developer ($99/year) sometime in the spring Get an iOS device (3rd or 4th generation iPod Touch, iPhone 3GS/ iPhone4, iPad)
  40. 40. May you and yours have a wonderful Christmas holiday!
  41. 41. See you in 2011! 42

×