Objective-C

/** 原文件 */
// Person.h
#import <Foundation/Foundation.h> @interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@end // Person.m
#import "Person.h" @implementation Person
- (instancetype)init {
if (self = [super init]) {
_name = @""; NSLog(@"%@", [self class]); // Person
NSLog(@"%@", [super class]); // Person
}
return self;
} - (void)dealloc {
NSLog(@"Call dealloc in Person.m");
}
@end
/** Category文件*/
// Person+Category.h
#import "Person.h" @interface Person (Category)
// 添加属性address
@property (nonatomic, copy) NSString *address;
@end // Person+Category.m
#import "Person+Category.h"
#import <objc/runtime.h> @implementation Person (Category) static void *addressKey = &addressKey; #pragma mark - OC 在Category关联属性
- (void)setAddress:(NSString *)address {
objc_setAssociatedObject(self, &addressKey, address, OBJC_ASSOCIATION_COPY_NONATOMIC);
} - (NSString *)address {
return objc_getAssociatedObject(self, &addressKey);
} /** 在category里面执行dealloc方法后,Person类文件里的dealloc会不执行 */
- (void)dealloc {
objc_removeAssociatedObjects(self);
NSLog(@"remove associated");
}
@end
// test
#import "Person+Category.h" Person *p = [Person new];
p.name = @"xiaoMing";
p.address = @"gz";
NSLog(@"name is: %@, address is: %@", p.name, p.address);

Swift

// .swift文件
import Cocoa class Car {
var name = ""
} private var priceKey: Void?
extension Car {
/// car's price
var price: Double? {
get {
return objc_getAssociatedObject(self, &priceKey) as? Double
}
set {
objc_setAssociatedObject(self, &priceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
} let c1 = Car()
c1.name = "su"
c1.price = 110000.1
print("c1's name is: \(c1.name) and price is: \(c1.price!)")

最新文章

  1. SpringMvc中初始化参数绑定
  2. Web Worker 是什么鬼?
  3. Ajax例子,views返回,html接收数据
  4. 我为什么期待M#?
  5. 水果姐逛水果街Ⅰ(codevs 3304)
  6. Add Customerlize Button in More Button List In Odoo
  7. django 用imagefiled访问图片
  8. Android之点击切换图片
  9. CH Round #45 能量释放
  10. [React] React Router: Named Components
  11. BOM操作写法实例
  12. mac webstrom在线激活
  13. C++编译连接过程中关于符号表的报错分析
  14. [Swift]LeetCode686. 重复叠加字符串匹配 | Repeated String Match
  15. python小程序打包
  16. centos7 搭建openvpn服务器
  17. chrome.debugger
  18. SQL like 模糊查询, in
  19. [Tensorflow] RNN - 02. Movie Review Sentiment Prediction with LSTM
  20. SAS获取最后一条观测到指定宏

热门文章

  1. Visual Studio调试XSLT
  2. time、datetime
  3. 单例模式-DCL双重锁检查实现及原理刨析
  4. 【CSP-S膜你考】不怕噩梦 (模拟)
  5. ZROI 暑期高端峰会 A班 Day5 杂题选讲
  6. 【cf补题记录】Codeforces Round #608 (Div. 2)
  7. pose_graph的优化变量和优化函数
  8. c++隐式转换(implicit conversion)
  9. Kubernetes集群之清除集群
  10. Angular Material