今天咱們詳細的講一下類目,所謂類目就是爲已存在的類添加方法,但是不能添加成員變量。
首先爲NSString添加分類
首先到xcode裏面,直接上圖
#import <Foundation/Foundation.h>
@interface NSString (module)
- (int)calculationTheNumberOfArabicNumeralsInString;
+ (int)calculationTheNumberOfArabicNumeralsWithString:(NSString *)string;
+ (void)test;
@end
@implementation Person
+ (void)test{
NSLog(@"Person---test");
}
@end
#import "NSString+module.h"
@implementation NSString (module)
- (int)calculationTheNumberOfArabicNumeralsInString{
int count = 0;
for (int i = 0; i < self.length; i++) {
char a = [self characterAtIndex:i];
if (a >= '0' && a <= '9') {
count++;
}
}
return count;
}
+ (int)calculationTheNumberOfArabicNumeralsWithString:(NSString *)string{
return [string calculationTheNumberOfArabicNumeralsInString];
}
NSString+module.h裏面的module是爲工程裏面哪個模塊添加分類這樣在ViewController.m裏面
NSString *str = @"123flahfho1234567";
int num = [str calculationTheNumberOfArabicNumeralsInString];
int num1 = [NSString calculationTheNumberOfArabicNumeralsWithString:str];
NSLog(@"調用對象方法這個字符串中的阿拉伯數字的個數是%d個",num);
NSLog(@"調用類方法這個字符串中的阿拉伯數字的個數是%d個",num1);
//打印結果如下:
// 2017-07-13 11:03:47.114 分類又叫類目[65722:826033] 調用對象方法這個字符串中的阿拉伯數字的個數是10個
// 2017-07-13 11:03:53.313 分類又叫類目[65722:826033] 調用類方法這個字符串中的阿拉伯數字的個數是10個
到這裏就爲NSStirng添加了一個分類但是有的同學可能有疑問,就是類裏面的方法和分類裏面的方法能不能名字一樣?答案是可以方法名相同,但是問題來了,到底是調用哪個同名方法呢以及它們的優先級誰高誰低?好的,下面我們一起來探究一下
首先創建一個繼承於NSObject的Person類,並且爲裏面添加方法:
#import <Foundation/Foundation.h>
@interface Person : NSObject
+ (void)test;
@end
#import "Person.h"
@implementation Person
+ (void)test{
NSLog(@"Person---test");
}
@end
再爲這個類創建兩個分類
#import "Person.h"
@interface Person (First)
+ (void)test;
@end
#import "Person+First.h"
@implementation Person (First)
+ (void)test{
NSLog(@"Person+First.h---test");
}
@end
#import "Person.h"
@interface Person (Second)
+ (void)test;
@end
#import "Person+Second.h"
@implementation Person (Second)
+ (void)test{
NSLog(@"Person+Second.h---test");
}
@end
[Person test];
打印結果如下:
2017-07-13 11:17:20.446 分類又叫類目[65844:832770] Person+Second.h---test
說明分類的優先級是高於類本身的方法,但是究竟是哪個分類的優先級高呢,還得看這裏,如圖所以綜上所述
分類的優先級 > 自身類,至於那個分類的優先級高,那就得看先加載哪個分類的.m文件了,唉!