// // Animal.h // CategoryProtocol // // Created by God Lin on 14-11-26. // Copyright (c) 2014年 hust. All rights reserved. // #ifndef CategoryProtocol_Animal_h #define CategoryProtocol_Animal_h // 定义协议 @protocol Animal <NSObject> // default is required @required -(void)showName; @optional -(void)showOptional; @end #endif
// // Cat+speak.h // CategoryProtocol // // Created by God Lin on 14-11-26. // Copyright (c) 2014年 hust. All rights reserved. // #import <Foundation/Foundation.h> #import "Cat.h" // 定义分类,注意语法,且只能写方法 @interface Cat (speak) -(void)speak; @end
//
//  Cat+speak.m
//  CategoryProtocol
//
//  Created by God Lin on 14-11-26.
//  Copyright (c) 2014年 hust. All rights reserved.
//
#import "Cat+speak.h"
// 实现分类,能直接访问类属性
@implementation Cat (speak)
-(void)speak
{
    NSLog(@"%@ : 喵喵", name);
}
@end
//
//  Cat.h
//  CategoryProtocol
//
//  Created by God Lin on 14-11-26.
//  Copyright (c) 2014年 hust. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Animal.h"
// 类实现协议
@interface Cat : NSObject <Animal>
{
    NSString*   name;
}
@property NSString* name;
-(void)showName;
@end
//
//  Cat.m
//  CategoryProtocol
//
//  Created by God Lin on 14-11-26.
//  Copyright (c) 2014年 hust. All rights reserved.
//
#import "Cat.h"
@implementation Cat
@synthesize name;
-(void)showName
{
    NSLog(@"%@", name);
}
@end
//
//  main.m
//  CategoryProtocol
//
//  Created by God Lin on 14-11-26.
//  Copyright (c) 2014年 hust. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Cat+speak.h"
int main(int argc, const char * argv[])
{
    @autoreleasepool
    {
        Cat* cat = [[Cat alloc] init];
        
        [cat setName:@"HelloKity"];
        [cat showName];
        [cat speak];
        
    }
    return 0;
}
2014-11-26 22:32:45.488 CategoryProtocol[1741:303] HelloKity 2014-11-26 22:32:45.490 CategoryProtocol[1741:303] HelloKity : 喵喵
原文:http://blog.csdn.net/arbboter/article/details/41524815