iOS 重构:OC 分类属性懒加载

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];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AGI阅读 16,009评论 3 119
  • by 宇风不停 无意中得知张爱玲是天秤座的,所以想要更深入的了解美丽的她。她具有典型的天枰座的性格特点,高...
    宇风不停阅读 677评论 0 1
  • 我们都知道,目前自媒体以今日头条、大鱼、百度百家、企鹅等平台为首,不管是获取平台流量费还是树立自我平台非常不错的,...
    98880994f6db阅读 289评论 0 0
  • 同学们,好久没看到我的推送了吧哈哈。广东前些天降温得厉害,冻得让人仿佛思考都停止了,走出家门到周边闲逛实在需要莫大...
    木槿朝荣阅读 202评论 0 0
  • 今天的话比较多,已经写到第三篇了 晚间,我和邓经理在房间,遥控板拿在手里,选呀选的,终于看见了一部不错的电影《狼少...
    那个姑娘阅读 173评论 0 0