举例: 给系统自带的类扩充方法:
给NSString类添加类方法,计算数字的个数
给NSString类添加对象方法,计算数字的个数
main.m:
#import <Foundation/Foundation.h>
#import"NSString+NUmber.h"
int main()
{
int count = [NSString numberCounterOfString: @"ahfioahioew"]; //类方法
int count = [@"hdfuiha" numberCount]; //对象方法
NSLog(@"%d", count);
return 0;
}
NSString+NUmber.h:
#import<Foundation/Foundation.h>
@interface NSString (Number)
+ (int)numberCountOfString: (NSString *)str;
- (int)numberCount;
@end
NSString+Number.m:
#import "NSString+NUmber.h"
@implemention NSString (Number)
+ (int)numberCountOfString: (NSString *)str
{
return [str numberCount];// 在类方法中调用对象方法
}
- (int)numberCount
{
int count = 0;
for (int i = 0; i<self.length; i++)
{ //取出i这个位置对应的数字
unichar c = [self characterAtIndex:i];
if (c>='0' && c<='9')
{
count ++;
}
return count;
}
}
@end
|
|