问题 用objc_msgSend分开发送alloc init则正确运行,一起发送就crash了,请问下是为什么,而且只是在添加到self.view的时候才crash?
//最后一行出错
UIView *view = ((UIView *(*)(id,SEL,SEL))objc_msgSend)([UIView class],@selector(alloc),@selector(init));
((void (*)(id,SEL,CGRect))objc_msgSend)(view,@selector(setFrame:),self.view.bounds);
((void (*)(id,SEL,UIColor *))objc_msgSend)(view,@selector(setBackgroundColor:),[UIColor orangeColor]);
((void (*)(id,SEL,id))objc_msgSend)(self.view,@selector(addSubview:),view);//Thread 1:EXC_BAD_ACCESS(code=1,adress=0x0)
//正确运行
UIView *view = ((UIView *(*)(id,SEL))objc_msgSend)([UIView class],@selector(alloc));
view = ((UIView *(*)(id,SEL))objc_msgSend)(view,@selector(init));
((void (*)(id,SEL,CGRect))objc_msgSend)(view,@selector(setFrame:),self.view.bounds);
((void (*)(id,SEL,UIColor *))objc_msgSend)(view,@selector(setBackgroundColor:),[UIColor orangeColor]);
((void (*)(id,SEL,id))objc_msgSend)(self.view,@selector(addSubview:),view);
你第一行并没有
init
,只是把 @selector(init) 做为alloc
方法的参数了,等价于:然而
alloc
方法是没有参数的,在运行时忽略了