Ray's playground

 

Categories and Protocols(Chapter 11 of Programming in Objective-C 2.0)

code
1 #import “Fraction.h”
2 @interface Fraction (MathOps)
3 -(Fraction *) add: (Fraction *) f;
4 -(Fraction *) mul: (Fraction *) f;
5 -(Fraction *) sub: (Fraction *) f;
6 -(Fraction *) div: (Fraction *) f;
7 @end

 

  This interface section tells the compiler you are adding an extension to the class called Fraction under the category named MathOps.The MathOps category contains four instance methods: add:, mul:, sub:, and div:. Each method takes a fraction as its argument and returns one as well. 

  Some points about categories are worth mentioning. First, although a category has access to the instance variables of the original class, it can’t add any of its own. If you need to do that, consider subclassing. Also, a category can override another method in the class, but this is typically considered poor programming practice. 

1 @protocol Drawing
2 -(void) paint;
3 -(void) erase;
4 @optional
5 -(void) outline;
6 @end

 

 

  Note the use of the @optional directive here. Any methods that are listed following that directive are optional. That is, an adopter of the Drawing protocol does not have to implement the outline method to conform to the protocol. (And you can subsequently switch back to listing required methods by using the @required directive inside the protocol definition.) 

posted on 2010-10-18 21:37  Ray Z  阅读(264)  评论(0编辑  收藏  举报

导航