Objective-C - 分类(类别)的应用 Category
分类(类别)的应用 Category
#import "Person.h"
#import "Person+One.h"
#import "Person+Two.h"
int main()
{
Person *p = [[Person alloc] init];
[p test];
return 0;
}
主类
@interface Person : NSObject
{
int _age;
}
@property int age;
- (void)test;
@end
@implementation Person
- (void)test
{
NSLog(@"Person-test");
}
@end
分类一
#import "Person.h"
@interface Person (One)
- (void)test2;
@end
#import "Person+One.h"
@implementation Person (One)
- (void)test2
{
NSLog(@"-----test2");
}
- (void)test
{
NSLog(@"Person (One)-test");
}
@end
分类二
#import "Person.h"
@interface Person (Two)
- (void)study;
@end
#import "Person+Two.h"
@implementation Person (Two)
- (void)study
{
NSLog(@"学习-----%d", _age);
}
- (void)test
{
NSLog(@"Person (Two)-test");
}
@end
分类的应用
#import <Foundation/Foundation.h>
@interface NSString (Number)
+ (int)numberCountOfString:(NSString *)str;
- (int)numberCount;
@end
@implementation NSString (Number)
+ (int)numberCountOfString:(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;
return [str numberCount];
}
- (int)numberCount
{
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
#import <Foundation/Foundation.h>
#import "NSString+Number.h"
int main()
{
int count = [@"9fdsfds543543" numberCount];
NSLog(@"%d", count);
return 0;
}