您的位置:首页 > 编程语言 > Go语言

101,使用Category给API里面的类添加新方法

2015-12-18 11:23 429 查看


NSString+JS.h:

#import <Foundation/Foundation.h>

@interface NSString (JS)

+(int)countWithStr:(NSString *)str;

-(int)count;

@end
NSString+JS.m:

#import "NSString+JS.h"

@implementation NSString (JS)

+(int)countWithStr:(NSString *)str{

int count = 0;

for (int i =
0; i < str.length; i++) {

unichar c = [str
characterAtIndex:i];

if (c >= '0' && c <=
'9') {

count++;

}

}

return count;

}

-(int)count{

//self:谁调用该函数就是谁

int count = 0;

for (int i =
0; i < self.length; i++) {

unichar c = [self
characterAtIndex:i];

if (c >= '0' && c <=
'9') {

count++;

}

}

return count;

}

@end

main.m:

#import <Foundation/Foundation.h>

#import "NSString+JS.h"

int main(int argc,
const char * argv[]) {

/*

问题:计算字符串中含有多少个数字?

知识点:为NSString添加计算数字的方法

*/

NSString *str =
@"s123asf675ds3s5";

int count = [NSString
countWithStr:str];

int count1 = [str
count];

NSLog(@"count = %i,count1 = %i",count,count1);

return 0;

}

//2015-12-18 11:18:29.492 8,使用Category为系统类添加方法[982:50190] count = 8,count1 = 8

//Program ended with exit code: 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: