Protocol例子


@protocol Printing-(void)print;@end ////  Book.h #import <Cocoa/Cocoa.h>#import "printing.h" @interface Book : NSObject <Printing> {	NSString* bookname;} @property (retain) NSString* bookname; -(id)initWithBookname:(NSString*)name;@end ////  Book.m #import "Book.h"  @implementation Book @synthesize bookname; -(void)print{	NSLog(@"%@", self.bookname);} -(id)initWithBookname:(NSString*)name{	self = [super init];	if(nil!=self){		self.bookname = name;	}	return self;} -(void)dealloc{	[bookname release];	[super dealloc];} @end //main.m #import <Foundation/Foundation.h>#import "Book.h" int main (int argc, const char * argv[]) {NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];	NSString* bookname = [[NSString alloc]initWithFormat:@"Twilight"];	Book* book = [[Book alloc]initWithBookname:bookname];	[bookname release]; 	if([book conformsToProtocol:@protocol(Printing)]){		[book print];	} 	[book release];    [pool drain];    return 0;}
分类:Mac技巧、标签:, 、收藏链接 本文地址.