iOS开发中EXC_BAD_ACCESS的另类原因

时间:2021-06-11 06:15:11

今天偶然学习iOS开发的时候碰到一个EXC_BAD_ACCESS的异常,经查资料得到的解释是由于访问了已经被回收了堆内存对象导致的,参考:

http://code.tutsplus.com/tutorials/what-is-exc_bad_access-and-how-to-debug-it--cms-24544

不过我的这个例子却不是因为这个原因导致的,请看例子:

 #import <Foundation/Foundation.h>

 @interface MyRectangle : NSObject

 -(void) setWidth: (int) width;

 -(void) setHeight: (int) height;

 -(void) setWidth:(int)width andHeight: (int) height;

 -(int) area;

 @end

 // Implemention

 #import "MyRectangle.h"

 @implementation MyRectangle {
int width;
int height;
} -(void) setWidth: (int) w {
width = w;
} -(void) setHeight: (int) h {
height = h;
} -(void) setWidth:(int)w andHeight: (int) h {
width = w;
height = h;
} -(int) area {
return width * height;
} @end

main函数

 #import <Foundation/Foundation.h>
#import "MySquare.h" int main(int argc, const char * argv[]) {
@autoreleasepool {
// 反射
MyRectangle *rect = [[MyRectangle alloc] init];
[rect setWidth:];
[rect setHeight:]; id x_id = [rect performSelector:@selector(area)];
NSLog(@"selector got area is %@", x_id);
}
return ;
}

原因就在于area返回的是一个int类型的数据,int类型其实是一个放在栈内存的值,把它赋给类型为id变量,id变量的意思是:编译器把它当成任意的对象类型。这样话的话,运行的时候area方法得到的值返回给x_id,然后再拿这值当作堆内存的地址,这里当然找不到此数据了,就会导致访问失败的错误了。

从上面的例子可以看出EXC_BAD_ACCESS异常的本意是指访问不到内存中这个地址的值,可能是由于些变量已经被回收了,亦可能是由于使用栈内存的基本类型的数据赋值给了id类型的变量。