水果官方给出的分类,即Category是不能添加属性的,但是我们是谁;我们有黑魔法啊,runtime 操练起来啊
从xcode6开始到xcode 7创建分类都要在
command+N,之后选中Objective -C File,然后选中你要给谁创建分类,给谁的分类添加属性。
我这里选择万象“NSObject”
.h
// NSObject+IndieBandName.h
// CategoryAddVar
//
// Created by Vizard on 16/7/28.
// Copyright © 2016年 Vizard. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSObject (IndieBandName)
@property (nonatomic, strong) NSString *indieBandName;
@end
.m
// NSObject+IndieBandName.m
// CategoryAddVar
//
// Created by Vizard on 16/7/28.
// Copyright © 2016年 Vizard. All rights reserved.
//
#import "NSObject+IndieBandName.h"
#import <objc/runtime.h>
static const void *IndieBanNameKey = &IndieBanNameKey;
@implementation NSObject (IndieBandName)
@dynamic indieBandName;
- (NSString *)indieBandName
{
return objc_getAssociatedObject(self, IndieBanNameKey);
}
- (void)setIndieBandName:(NSString *)indieBandName
{
objc_setAssociatedObject(self, IndieBanNameKey, indieBandName, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
然后在VC中
就可以使用了。
相信看官看到这里已经看透了,黑魔法的关键点了
1.#import <objc/runtime.h>
2.@dynamic indieBandName;
3. objc_getAssociatedObject
4. objc_setAssociatedObject