0

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.

gadgetmo
  • 3,058
  • 8
  • 27
  • 41

1 Answers1

4

I think the problem is string format in NSString, you should change the code to :

[result setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d", rNumber]]];

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.

Lunayo
  • 538
  • 7
  • 32
  • Thanks for the answer. I have Xcode 4.2 with ARC (Automatic Reference Counting). Do I still have to release them? – gadgetmo Oct 27 '11 at 09:01
  • Will it release on `viewWillDisappear` when using ARC? – gadgetmo Oct 27 '11 at 09:11
  • 2
    yes it will, try read here http://stackoverflow.com/questions/6385212/how-does-the-new-automatic-reference-counting-mechanism-work – Lunayo Oct 27 '11 at 09:16