转自Anselz的博客
- RuntimeObj *obj = [[RuntimeObj alloc]init];
- [obj setValue:@"value4Name" forKey:@"objName"];//RuntimeObj 没有objName这个属性
- -(BOOL)hasAttribute:(NSString *)attName
- {
- BOOL flag = NO;
- u_int count;
- Ivar *ivars = class_copyIvarList([self class], &count);
- for (int i = 0; i < count ; i++)
- {
- const char* propertyName = ivar_getName(ivars[i]);
- NSString *strName = [NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding];
- if ([attName isEqualToString:strName]) {
- flag = YES;
- }
- NSLog(@"===%@",strName);
- }
- return flag;
- }
- objc_property_t* properties= class_copyPropertyList([self 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);
- }
- void dynamicMethod(id self, SEL _cmd)
- {
- printf("SEL %s did not exist\n",sel_getName(_cmd));
- }
- + (BOOL) resolveInstanceMethod:(SEL)aSEL
- {
- class_addMethod([self class], aSEL, (IMP)dynamicMethod, "v@:");
- return YES;
- }
- void dynamicMethod(id self, SEL _cmd)
- {
- printf("SEL %s did not exist\n",sel_getName(_cmd));
- }
- + (BOOL) resolveInstanceMethod:(SEL)aSEL
- {
- class_addMethod([self class], aSEL, (IMP)dynamicMethod, "v@:");
- return YES;
- }
- RuntimeObj *obj = [[RuntimeObj alloc]init];
- [obj performSelector:@selector(dynamicMethod:)];
注:IMP 是函数指针 |
- void demoReplaceMethod(id SELF, SEL _cmd)
- {
- NSLog(@"demoReplaceMethod");
- }
- -(void)replaceMethod
- {
- Class strcls = [self class];
- SEL targetSelector = @selector(targetRelplacMethod);
- class_replaceMethod(strcls,targetSelector,(IMP)demoReplaceMethod,NULL);
- }
- -(void)targetRelplacMethod
- {
- NSLog(@"targetRelplacMethod");
- }
- RuntimeObj *obj = [[RuntimeObj alloc]init];
- [obj replaceMethod];
- [obj targetRelplacMethod];
- 2014-05-12 19:38:37.490 Runtime[1497:303] demoReplaceMethod
- //挂载对象所需要的参数(UIAlertView挂载对象)
- static const char kRepresentedObject;
- -(void)showAlert:(id)sender
- {
- UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去看看", nil];
- alert.tag = ALERT_GOTO_TAG;
- objc_setAssociatedObject(alert, &kRepresentedObject,
- @"我是被挂载的",
- OBJC_ASSOCIATION_RETAIN_NONATOMIC);
- [alert show];
- }
- -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
- {
- if (buttonIndex == 1) {
- NSString *str = objc_getAssociatedObject(alertView,
- &kRepresentedObject);
- NSLog(@"%@",str)
- }
- }