Object-c中的Category特性全部在此.

apple文檔中瞭解到Object-c的Category的作用僅有一個:
* 向現有的類中添加方法(添加任意個數)

// NSString+log.h
@interface NSString (log)
-(void) log;
@end


// NSString+log.m
@implementation NSString (log)
-(void) log {
    NSLog(@"log!");
}
@end

就這樣, 就實現了向NSString 類中添加了log方法.


Category 是不可以重寫原始類的方法的, 比如

@interface NSOperation(main)
-(void) main;
@end

@implementation NSOperation(main)

-(void) main{ //這裏會有一個警告: "Category is implementing a method which will also be implemented by its primary class"
    
}
所以,  這裏要想重寫main方法, 就必須在子類中重寫. (Object-c只支持單繼承).

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章