EXC_BAD_ACCESS致命错误
我有这个创建图像的代码:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
background = [[UIImageView alloc]initWithFrame:CGRectMake(150, 60, 180, 180)];
result = [[UIImageView alloc]initWithFrame:CGRectMake(150, 60, 180, 180)];
[background setImage:[UIImage imageNamed:[defaults objectForKey:@"colour"]]];
[self.view addSubview:background];
[self.view insertSubview:result aboveSubview:background];
这是在我的 viewWillAppear
中。当我按下按钮时,会发生这种情况:
- (IBAction)oneToSix {
int rNumber = (arc4random() % 6) + 1;
[result setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@", rNumber]]];
}
但是当我按下按钮时,它会出现致命错误:线程一:程序收到信号:“EXC_BAD_ACCESS”。
在setImage
部分。问题是什么?我是 Objective C 的新手。
I have got this code which creates an image:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
background = [[UIImageView alloc]initWithFrame:CGRectMake(150, 60, 180, 180)];
result = [[UIImageView alloc]initWithFrame:CGRectMake(150, 60, 180, 180)];
[background setImage:[UIImage imageNamed:[defaults objectForKey:@"colour"]]];
[self.view addSubview:background];
[self.view insertSubview:result aboveSubview:background];
This is in my viewWillAppear
. When I press a button, this happens:
- (IBAction)oneToSix {
int rNumber = (arc4random() % 6) + 1;
[result setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@", rNumber]]];
}
But it gets this fatal error: Thread one: Program received signal: "EXC_BAD_ACCESS".
on the setImage
part when I press the button. What is the problem? I am new to Objective C.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为问题是 NSString 中的字符串格式,您应该将代码更改为 :
因为 rNumber 是 int。
并且您应该释放背景和结果,因为每次出现视图时都会调用 viewWillAppear ,因此会导致内存泄漏。
I think the problem is string format in NSString, you should change the code to :
as rNumber is an int.
And you should release the background and result, as viewWillAppear will tend to be called every time the view is appear so will result a memory leak.