关联对象

63 阅读1分钟
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UINavigationController (Cloudox)

@property (nonatomic,copy) NSString *cloudox;

@end

NS_ASSUME_NONNULL_END
///===================================================
#import "UINavigationController+Cloudox.h"
#import <objc/runtime.h>

//定义常量 必须是C语言字符串
static char *CloudoxKey = "CloudoxKey";

@implementation UINavigationController (Cloudox)

- (void)setCloudox:(NSString *)cloudox {
    objc_setAssociatedObject(self, CloudoxKey, cloudox, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)cloudox {
    return objc_getAssociatedObject(self, CloudoxKey);
}

@end
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end
///===========================================
#import "ViewController.h"
#import "UINavigationController+Cloudox.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"Demo";
    self.view.backgroundColor = [UIColor lightGrayColor];
    
    // 给UINavigationController新加的属性赋值
    self.navigationController.cloudox = @"Hey,this is category's new property!";
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width-300)/2, 100, 300, 50)];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = self.navigationController.cloudox;
    [self.view addSubview:label];
}

@end