In order to understand IMP
, I wrote some test codes and found a problem in the process of testing.
I got a surprise
Here is the code.
@interface Test : NSObject
@property (nonatomic, copy) NSString *name;
@end
@implementation Test
- (NSString *)description{
return [[super description] stringByAppendingString:self.name];
}
- (void)dealloc{
NSLog(@"Test dealloc %@",self);
}
- (void)test:(NSString *)str{
NSLog(@"- (void)test %@",str);
}
+ (void)test:(NSString *)str{
NSLog(@"+ (void)test %@",str);
}
- (void)test{
NSLog(@"- (void)test");
}
+ (void)test{
NSLog(@"+ (void)test");
}
@end
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// IMP imp = [[Test new] methodForSelector:@selector(test:)];
// NSLog(@"%p",imp);
// IMP imp1 = [Test instanceMethodForSelector:@selector(test)];
IMP imp2 = [Test methodForSelector:@selector(test:)];
// NSLog(@"%p",imp2);
imp2();
NSLog(@"%p",imp2);
// imp2 = [Test methodForSelector:@selector(test)];
// imp2();
// imp();
// imp = [[Test new] methodForSelector:@selector(test:)];
// NSLog(@"%p",imp);
// imp();
// imp1();
// imp1();
// imp2();
// imp2();
// void (*func)(id,SEL,NSString *) = (void *)imp;
// func([Test class],@selector(test:),@"");
// void (*func1)(id,SEL,NSString *) = (void *)imp1;
// func1([Test class],@selector(test:),@"ha");
// void (*func2)(id,SEL,NSString *) = (void *)imp2;
// func2([Test class],@selector(test:),@"haha");
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
There's no problem when I run a single IMP
.But when I run more than one IMP
will crash for BAC_ACCESS
and it only happens with the function which has arguments.So,why it can work with one and crash with two.