iOS 分类属性实现懒加载
(用途: 项目重构, 继承->组合)
//UIViewController+AddView.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIViewController (AddView)
@property (nonatomic, strong, readonly) UITableView *tbView;
@end
NS_ASSUME_NONNULL_END
//UIViewController+AddView.m
#import "UIViewController+AddView.h"
#import <objc/runtime.h>
@implementation UIViewController (AddView)
- (UITableView *)tbView{
id obj = objc_getAssociatedObject(self, _cmd);
if (obj) {
return obj;
}
UITableView *table = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
[table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
table.estimatedRowHeight = 0;
table.estimatedSectionHeaderHeight = 0;
table.estimatedSectionFooterHeight = 0;
if ([self conformsToProtocol:@protocol(UITableViewDataSource)]) table.dataSource = self;
if ([self conformsToProtocol:@protocol(UITableViewDelegate)]) table.delegate = self;
objc_setAssociatedObject(self, _cmd, table, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return table;
}
🌰🌰:
#import "EntryViewController.h"
@interface EntryViewController ()<UITableViewDataSource, UITableViewDelegate>
@end
@implementation EntryViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.view addSubview:self.tbView];
}