前幾天在做自定義TableCell,感覺突然需要一個Resize,需要點自由的空間,在網上搜索了一下:
#import <UIKit/UIKit.h>
@interface UIImage(Resize)
-(UIImage*)resize:(CGRect)rect;
@end
#import "UIImageUtil.h"
@implementation UIImage(Resize)
-(UIImage*)resize:(CGRect)rect{
...
}
@end
就是這麼簡單,UIImage就擁有了可變大小。尤其在對系統類或者第三方庫進行擴展的時候,不需要繼承就可以添加新的方法。
使用Category需要注意幾點:
- Category的方法不一定在@Implementation中實現,可以在其他位置實現,但必須在繼承樹中可見
- Category中理論上不能聲明額外的變量,但是可以使用原有類中的變量
- Category中如需添加新的變量可以使用@dynamic來補充
可以參考Apple官方文檔
Extension和Category的區別:
- Extension更像是匿名的Category
- Extension中的方法必須在@Implementation中實現
- Extension可以聲明新的變量
代碼示例:
@interface MyClass : NSObject
- (float)value;
@end
@interface MyClass () {
float value;
}
- (void)setValue:(float)newValue;
@end
@implementation MyClass
- (float)value {
return value;
}
- (void)setValue:(float)newValue {
value = newValue;
}
@end