1、对象拷贝:id object_copy(id obj, size_t size) / 对象释放 id object_dispose(id obj)
TsetClass *obj = [TsetClassnew];
id objTest =object_copy(obj,sizeof(obj));
(lldb)po &obj
0x00007fff54a7cb08
(lldb)po &objTest
0x00007fff54a7cb00
无疑问打印的内存地址不是一样的,此方法类似指针的深拷贝,
(1)关于对象的深拷贝,浅拷贝还有必要说一下
<1>深拷贝以及浅拷贝
浅复制尽复制对象本身,对象里的属性、包含的对象不做复制
深复制复制全部,包括对象的属性和其他对象
Foundation框架支持复制的类,默认是浅复制
<2>对象的自定义拷贝
对象拥有复制特性,必须实现NSCopying,NSMutableCopying协议,实现该协议的copyWithZone方法和mutableCopyWithZone方法
深拷贝和浅拷贝的区别就在于copyWithZone方法的实现
object_dispose(objTest);//等价于[objTest release];此方法只是对runtime的封装
再次执行 [objTest release]都晓得报的什么错误;
list:
TestRuntime(1034,0x111b66300) malloc: *** error for object 0x7ffe1a75b940: pointer being freed was not allocated
2.更改对象的类/获取对象的类 | Class object_setClass(id obj, Class cls) / Class object_getClass(id obj)
(1) 更改对象的类
TsetClass *obj1 = [TsetClass new];
Class aClass =object_setClass(obj1, [CustomClassOther class]);
(lldb)po obj1
<CustomClassOther: 0x7f8e4bd14480>
(lldb) po aClass
TsetClass
有没有出乎你的想象0.0.
(2)获取对象的类
TsetClass *obj2 = [TsetClass new];
Class aLogClass =object_getClass(obj2);
(lldb) po aLogClass
TsetClass
NSString *className = [NSStringstringWithCString:object_getClassName(obj2)encoding:NSUTF8StringEncoding];
NSLog(@"className:%@", className);
(lldb) po className
TsetClass
3、给一个类添加方法 BOOL class_addMethod(Class cls,SEL name,IMP imp, const char *types)
TsetClass *instance = [[TsetClassalloc]init];
方法添加
class_addMethod([TsetClass class],@selector(ocMethod:), (IMP)cfunction,"i@:@");
if ([instance respondsToSelector:@selector(ocMethod:)]) {
NSLog(@"Yes, instance respondsToSelector:@selector(ocMethod:)");
} else
{
NSLog(@"Sorry");
}
int a = (int)[instance ocMethod:@"我是一个OC的method,C函数实现"];
NSLog(@"a:%d", a);
int cfunction(id self, SEL _cmd, NSString *str) {
NSLog(@"%@", str);
return 520;//随便返回个值
}
4.获取一个类的所有方法/所有属性
(1)获取一个类的所有方法
u_int count;
Method* methods= class_copyMethodList([UIViewController class], &count);
for (int i = 0; i < count ; i++)
{
SEL name = method_getName(methods[i]);
NSString *strName = [NSString stringWithCString:sel_getName(name)encoding:NSUTF8StringEncoding];
// NSLog(@"%@",strName);
}
获取一个类的所有属性
u_int count;
objc_property_t *properties=class_copyPropertyList([TsetClass class], &count);
for (int i = 0; i < count ; i++)
{
const char* propertyName =property_getName(properties[i]);
NSString *strName = [NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding];
NSLog(@"%@",strName);
}
5.获取全局变量的值 (myFloat 为类的一个属性变量)
float myFloatValue;
object_getInstanceVariable(self,"myFloat", (void*)&myFloatValue);
NSLog(@"%f", myFloatValue);
6.设置全局变量的值
float newValue = 10.00f;
unsigned int addr = (unsigned int)&newValue;
object_setInstanceVariable(self,"myFloat", *(float**)addr);