總結(jié)
項(xiàng)目 | 類別(Category) | 類擴(kuò)展(Extension) |
---|---|---|
別名 | 分類 | 匿名分類 |
位置 | 單獨(dú)的.h .m文件中 | .m文件中@implementation的上面 |
命名 | @interface 類名 (分類名) | @interface 類名 () |
@property | 不能生成set毒坛、get方法 | 可以生成set哭当、get方法 |
使用環(huán)境 | 對(duì)框架的擴(kuò)展(沒(méi)有源碼涯贞,只能使用類別擴(kuò)展);或者對(duì)類的方法歸類 | 自定義類中創(chuàng)建私有變量和方法 |
此表格只是列舉一般情況
類別
main.m
#import <Foundation/Foundation.h>
#import "Category.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString *str = @"test";
[str function1];
[str method1];
}
return 0;
}
Category.h
#import <Foundation/Foundation.h>
//Function分類
@interface NSString (Function)
- (void)function1;
- (void)function2;
- (void)function3;
@end
//Method分類
@interface NSString (Method)
- (void)method1;
- (void)method2;
- (void)method3;
@end
Category.m
#import "Category.h"
//Function分類
@implementation NSString (Function)
- (void)function1 {
NSLog(@"fun1");
}
- (void)function2 {
NSLog(@"fun2");
}
- (void)function3 {
NSLog(@"fun3");
}
@end
//Method分類
@implementation NSString (Method)
- (void)method1 {
NSLog(@"met1");
}
- (void)method2 {
NSLog(@"met2");
}
- (void)method3 {
NSLog(@"met2");
}
@end
運(yùn)行結(jié)果
2016-09-28 21:56:53.139 Category[4043:370869] fun1
2016-09-28 21:56:53.140 Category[4043:370869] met1
類擴(kuò)展
main.m
#import <Foundation/Foundation.h>
#import "Extension.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Extension *ext = [[Extension alloc] init];
/**
* 正常践付,輸出"test1"
*/
[ext test1];
/**
* 正常,輸出"test1"
*/
NSLog(@"%@", ext.name1);
/**
* 報(bào)錯(cuò)瓦呼,test2是私有方法岖寞。
*/
// [ext test2];
/**
* 報(bào)錯(cuò)纽帖,name2是私有屬性
*/
// NSLog(@"%@", ext.name2);
}
return 0;
}
Extension.h
#import <Foundation/Foundation.h>
@interface Extension : NSObject
@property (nonatomic,copy) NSString *name1;
- (void) test1;
@end
Extension.m
#import "Extension.h"
@interface Extension ()
@property (nonatomic,copy) NSString *name2;
- (void)test2;
@end
@implementation Extension
- (void)test1 {
self.name1 = @"test1";
NSLog(@"%@", self.name1);
}
- (void)test2 {
self.name2 = @"test2";
NSLog(@"%@", self.name2);
}
@end