前面我们基本认识了类别是用来怎么用的, 那么现在我们来讲讲在实际开发中的一些事项, 其实在实际开发中, 类别用的最多的是给系统类添加方法的, 因为我们自己自定义的类灵活性比系统类要高, 而系统的类是固定死的, 如果给它添加方法, 我们只能选择使用类别, 下面让我们来看看~~
例子:
#import <Foundation/Foundaiton.h>
@interface NSString (Number)
@end
@implementation NSString (Number)
@end
int main()
{
return 0;
}上面就是我们给系统类NSString另外添加的方法, 现在我们有一个需求, 我要求, 设计一个类方法, 在输入的字符串, 要把里面的阿拉伯数字个数打印出来, 那么怎么添加呢?
下面让我们一起来看看:
#import <Foundation/Foundaiton.h>
@interface NSString (Number)
+ (int)numberCountOfString:(NSString *)string;
@end
@implementation NSString (Number)
+ (int)numberCountOfString:(NSString *)string
{
int count = 0;
for (int i = 0; i <= string.lenth; i++)
{
unichar c = [string characterAtIndex:i];
if (i = '0' && i = '9')
{
count++;
}
}
return count;
}
@end
int main()
{
int count = [NSString numberCountOfString:@"asdsa1231asd33123"];
NSLog(@"%d", count);
return 0;
}这样子就可以完成我们所需的结果啦~~~那如果我们要的是对象方法呢?? 我们下面继续来看看~~
#import <Foundation/Foundaiton.h>
@interface NSString (Number)
- (int)numberCount
@end
@implementation NSString (Number)
- (int)numberCount
{
int count = 0;
for (int i = 0; i < self.lenth; i++)
{
unichar c = [self characterAtIndex:i];
if (i = '0' && i = '9')
{
count++;
}
}
return count;
}
@end
int main()
{
int count = [@"oweq123oqwei94hsd1" numberCount];
NSLog(@"%d", count);
return 0;
}好了, 对象方法也出来了, 从上面的例子上看, 貌似对象方法更加的简单~~这个就是个人设计的问题了, 哪个方法简单, 我们就用哪个方法, 这个是我们一直推荐的思想.
好了, 这次我们就到这里了, 下次我们继续~~~