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

来源:互联网 发布:网络交友论坛 编辑:程序博客网 时间:2024/05/17 06:28

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 = [selfcharacterAtIndex: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 = [NSStringcountWithStr: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



0 0