使用运行时我们需要导入#import <objc/runtime.h>
我们看下面代码,也就是用C实现简单的set和get 方法
//
// NSObject+CategoryWithProperty.h
// RunTimeTest
//
// Created by plee on 15/10/8.
// Copyright © 2015年 franklee. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface NSObject (CategoryWithProperty)
@property (nonatomic,strong) NSObject * property;
@end
//
// NSObject+CategoryWithProperty.m
// RunTimeTest
//
// Created by plee on 15/10/8.
// Copyright © 2015年 franklee. All rights reserved.
//
#import "NSObject+CategoryWithProperty.h"
@implementation NSObject (CategoryWithProperty)
- (NSObject *)property{
return objc_getAssociatedObject(self, @selector(property));
}
- (void)setProperty:(NSObject *)property{
objc_setAssociatedObject(self, @selector(property), property, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
//
// ViewController.m
// RunTimeTest
//
// Created by plee on 15/10/8.
// Copyright © 2015年 franklee. All rights reserved.
//
#import "ViewController.h"
#import "NSObject+CategoryWithProperty.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSObject * object = [[NSObject alloc] init];
object.property = @"123";
NSLog(@"%@",object.property);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
- objc_getAssociatedObject 相当于iOS内部的get方法
OBJC_EXPORT id objc_getAssociatedObject(id object, const void *key)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1);
- id object : 关联对象
- const void *key: 我们需要定义一个常量void * 类型的key
- objc_setAssociatedObject 相当于iOS的属性的set方法
OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1);
1.id object :被关联的对象
2.const void *key :char 类型的key
3.id value :要被赋值的值
4.objc_AssociationPolicy policy :runtime内存管理有一下集几种
OBJC_ASSOCIATION_ASSIGN = 0, /**< Specifies a weak reference to the associated object. */
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /**< Specifies a strong reference to the associated object.
* The association is not made atomically. */
OBJC_ASSOCIATION_COPY_NONATOMIC = 3, /**< Specifies that the associated object is copied.
* The association is not made atomically. */
OBJC_ASSOCIATION_RETAIN = 01401, /**< Specifies a strong reference to the associated object.
* The association is made atomically. */
OBJC_ASSOCIATION_COPY = 01403
- OBJC_EXPORT void objc_removeAssociatedObjects(id object)
__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_1);
id object: 移除关联对象,用法不是很难,但是在使用中最好是合理使用,