OC基础--分类(category) 和 协议(protocol)

OC 中的category分类文件至关于 C#中的部分类;OC 中的protocol协议文件(本质是头文件)至关于 C#中的接口。今天就简单说明一下OC中的这两个文件。ui

因为视频中的Xcode版本低,致使了分类文件和协议文件没有找到,最后百度得知:atom

如图:Xcode 7.2版本中的category文件和protocol文件都归类到了Objective-C File 中spa

     

1、category文件:code

做用:能够扩展自定义类,或者系统类。下面的实例,是扩展了NSString 类,在类中扩展了计算字符串中数字个数的方法:视频

NSString类的分类的头文件对象

1 #import <Foundation/Foundation.h>
2 
3 @interface NSString (Number)
4 
5 // 计算字符串中阿拉伯数字的个数
6 - (int) numberCount;
7 
8 @end

NSString类的分类的.m文件blog

 1 #import "NSString+Number.h"
 2 
 3 @implementation NSString (Number)
 4 
 5 // @"abc123"
 6 - (int)numberCount
 7 {
 8     
 9     //[self length];
10     
11     int count = 0;
12     
13     int len = (int) self.length;
14     
15     for (int i = 0; i<len; i++) {
16         // 获取i位置对应的字符(char)
17        char c = [self characterAtIndex:i];
18         
19        if (c>='0' && c<='9')
20        {
21            count++;
22        }
23     }
24     
25     return count;
26 }
27 
28 @end

main文件:接口

 1 #import <Foundation/Foundation.h>
 2 #import "NSString+Number.h"
 3 
 4 int main(int argc, const char * argv[])
 5 {
 6 
 7     @autoreleasepool {
 8         
 9         NSString *str = @"abc 123fdsf090900sdfds68768867";
10         
11         int count = [str numberCount];
12         
13         NSLog(@"%d", count);
14     }
15     return 0;
16 }

2、protocol文件字符串

做用:声明一系列方法编译器

注意点:分类和协议都只能声明方法,不能声明成员变量

实例:

 1 // 声明一系列方法
 2 // 分类和协议都只能声明方法,不能声明成员变量
 3 @protocol MyProtocol
 4 
 5 // 默认是@required
 6 - (void) test4;
 7 
 8 @required // test1必须实现的
 9 - (void) test1;
10 
11 @optional  // test二、test3是可选实现的
12 - (void) test2;
13 - (void) test3;
14 
15 @end

 1>类遵照协议

@interface 类名:父类名<协议名称1,协议名称2>

@end

2>协议遵照协议

@protocol 协议名称<其余协议名称1,其余协议名称2>

@end

3>协议中方法声明的关键字

  (1)@required(默认)

  要求实现,若是没有实现,会发出警告

  (2)@optional

  不要求实现,

4>定义一个变量的时候,限制这个变量保存的对象遵照某个协议

类名<协议名称> *变量名;  或者

id<协议名称> 变量名;

实例:NSObject<MyProtocol> *obj;  或者

id<MyProtocol> obj2;

若是没有遵照相对应协议,编译器会警告

5>@property中声明的属性也可用来作一个遵照协议的限制

@property (nonatomic,strong) 类名<协议名称> *属性;

@property (nonatomic,strong) id<协议名称> 属性;

代码实例:

@property (nonatomic,strong) Dog<MyProtocol> *dog;

@property (nonatomic,strong) id<MyProtocol> dog2;

6>协议可用定义在单独.h文件中,也可用定义在某各种中

  (1)若是这个协议只用在某各种中,应该把协议定义在该类中

  (2)若是这个协议用在不少类中,就应该定义在单独文件中

7>分类也可用定义在单独.h和.m文件中,也可用定义在原来类中

  (1)通常状况下,都是定义在单独文件

  (2)定义在原来类中的分类,只要求能看懂语法

相关文章
相关标签/搜索