在分類中動態(tài)添加屬性
#import "NSObject+Associate.h"
#import <objc/runtime.h>
@interface NSObject()
@property (nonatomic,strong)id object;
@end
@implementation NSObject (Associate)
static char const * objectKey;
+ (void)test{
NSLog(@"test:%s",__func__);
}
- (void)setObject:(id)object{
objc_setAssociatedObject(self, objectKey, object,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (id)object{
return objc_getAssociatedObject(self, objectKey);
}
@end
知道這個后怎樣用在自己的分類之中呢?
- 給UIViewController 添加一分類
#import "UIViewController+Utils.h"
#import <objc/runtime.h>
const static char loadingViewKey;
@implementation UIViewController (Utils)
- (UIView *)loadingView {
return objc_getAssociatedObject(self, &loadingViewKey);
}
- (void)setLoadingView:(UIView *)loadingView {
objc_setAssociatedObject(self, &loadingViewKey, loadingView,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)showLoadingView {
if (!self.loadingView) {
UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
self.loadingView = loadingView;
[self.view addSubview:self.loadingView];
loadingView.center = CGPointMake(kScreenWidth / 2, (kScreenHeight - 20 - 44 * 2) / 2);
[loadingView startAnimating];
}
}
- (void)hideLoadingView {
if (self.loadingView) {
[self.loadingView removeFromSuperview];
}
}
在每次需要加載菊花的時候,使用
[self showLoadingView]
[self hideLoadingView]
- 這樣就不需要每次都去創(chuàng)建一個加載的菊花或者說是定義一個宏命令每次去創(chuàng)建調(diào)用了
- 有沒有幫助到你呢?點(diǎn)個贊吧