iOS 分类属性实现懒加载
(用途:项目重构,继承->组合)
创建控制器分类 UIViewController+Helper.h
.h文件
#import <UIKit/UIKit.h>
#import "AnimationObject.h"
@interface UIViewController (Helper)
@property (strong, nonatomic) UITableView *tableView;
+(AnimationObject *)animation;;
@end
.m文件
#import "UIViewController+Helper.h"
#import <objc/runtime.h>
@interface UIViewController ()<UITableViewDataSource,UITableViewDelegate>
@end
@implementation UIViewController (Helper)
@dynamic tableView;
+(AnimationObject *)animation{
AnimationObject * ani = objc_getAssociatedObject(self, _cmd);
if (!ani) {
ani = [[AnimationObject alloc]init];
objc_setAssociatedObject(self, _cmd, ani, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return ani;
}
- (UITableView *)tableView {
UITableView* table = objc_getAssociatedObject(self, _cmd);
if (table == nil) {
table = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
[table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
table.layer.borderColor = [UIColor grayColor].CGColor;
table.layer.borderWidth = 1;
table.delegate = self;
table.dataSource = self;
objc_setAssociatedObject(self, _cmd, table, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return table;
}
总结:tableView一类有代理方法的属性用非类方法;动画对象一类用类方法;
网友评论