在分类中动态添加属性
#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]
- 这样就不需要每次都去创建一个加载的菊花或者说是定义一个宏命令每次去创建调用了
- 有没有帮助到你呢?点个赞吧
网友评论