Objective-C之@类别小实例

循序渐进的类别小实例

内容大纲:

  • 1、小实例的问题需求和问题思路分析
  • 2、C语言模块化思想解决方法
  • 3、类别的使用
  • 4、开发经验者的类别用法

1、小实例的问题需求和问题思路分析:

已知一个字符串,要求找出字符串中所有的阿拉伯数字并计算其个数
     例如@"a123sb23r2jsowsalwf"求数字的个数
     1、计数器思想,定义一个变量保存结果
     2、遍历字符串,取出字符串中所有的字符

2、C语言模块化思想解决方法

 1 #import <Foundation/Foundation.h>
 2 
 3 int getStrCount(NSString* str)
 4 {
 5     int count = 0;
 6     for (int i = 0; i < str.length; i++) {
 7         unichar c = [str characterAtIndex:i];
 8         if (c >= '0' && c <= '9') {
 9             count++;
10         }
11     }
12     return count;
13 }
14 
15 int main(int argc, const char * argv[]) {
16     @autoreleasepool {
17         NSString* str = @"a123sb23r2jsowsalwf";
18         NSLog(@"%d",getStrCount(str));
19     }
20     return 0;
21 }

3、类别的使用

思路:因为是计算NSString对象的数字的个数,所以可以通过类别,将这个计算的功能作为NSSting的拓展方法。

创建NSString+getStrCount的类别

1 #import <Foundation/Foundation.h>
2 
3 @interface NSString (getStrCount)
4 
5 +(int)getStrCount:(NSString*)str;
6 
7 @end
 1 #import "NSObject+getStrCount.h"
 2 
 3 @implementation NSString (getStrCount)
 4 
 5 +(int)getStrCount:(NSString*)str{
 6     int count = 0;
 7     for (int i = 0; i < str.length; i++) {
 8         unichar c = [str characterAtIndex:i];
 9         if (c >= '0' && c <= '9') {
10             count++;
11         }
12     }
13     return count;
14 }
15 
16 @end

然后在客户端:

1 int main(int argc, const char * argv[]) {
2     @autoreleasepool {
3         NSString* str = @"a123sb23r2jsowsalwf";
4         NSLog(@"%d",[NSString getStrCount:str]);
5     }
6     return 0;
7 }

4、开发经验者的类别用法

NSString+getStrCount类别中

1 #import <Foundation/Foundation.h>
2 
3 @interface NSString (getStrCount)
4 
5 -(int)count;
6 
7 @end
 1 #import "NSObject+getStrCount.h"
 2 
 3 @implementation NSString (getStrCount)
 4 
 5 -(int)count{
 6     int count = 0;
 7     for (int i = 0; i < self.length; i++) {
 8         unichar c = [self characterAtIndex:i];
 9         if (c >= '0' && c <= '9') {
10             count++;
11         }
12     }
13     return count;
14 }
15 @end

然后在客户端:

1 int main(int argc, const char * argv[]) {
2     @autoreleasepool {
3         NSString* str = @"a123sb23r2jsowsalwf";
4         NSLog(@"%d",[str count]);
5     }
6     return 0;
7 }
 
posted @ 2015-11-03 01:23  何杨  阅读(256)  评论(0编辑  收藏  举报