// 修改isa,本质就是改变当前对象的类名
object_setClass(self, [XMGKVONotifying_Person class]);
// self动态添加关联
// id object:给哪个对象添加关联属性
// key:属性名
// value:关联值
//objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
objc_setAssociatedObject(self, @"observer", observer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
// self获取关联
//objc_getAssociatedObject(id object, const void *key)
id observer = objc_getAssociatedObject(self, @"observer");
默认情况下,如果是以[object message]的方式调用方法,如果object无法响应message消息时,编译器会报错。但如果是以perform…的形式来调用,则需要等到运行时才能确定object是否能接收message消息。如果不能,则程序崩溃。
通常,当我们不能确定一个对象是否能接收某个消息时,会先调用respondsToSelector:来判断一下。如下代码所示:
if ([self respondsToSelector:@selector(method)]) { [self performSelector:@selector(method)]; }
摘录其它博客:
@implementation HYBMethodLearn - (int)testInstanceMethod:(NSString *)name andValue:(NSNumber *)value { NSLog(@"%@", name); return value.intValue; } - (void)getMethods { unsigned int outCount = 0; Method *methodList = class_copyMethodList(self.class, &outCount); for (unsigned int i = 0; i < outCount; ++i) { Method method = methodList[i]; SEL methodName = method_getName(method); NSLog(@"方法名:%@", NSStringFromSelector(methodName)); // 获取方法的参数类型 unsigned int argumentsCount = method_getNumberOfArguments(method); char argName[512] = {}; for (unsigned int j = 0; j < argumentsCount; ++j) { method_getArgumentType(method, j, argName, 512); NSLog(@"第%u个参数类型为:%s", j, argName); memset(argName, '