UIPickerView EXC BAD ACCESS?

冷暖自知 提交于 2019-12-01 09:06:25
deanWombourne

You're not retaining your UIImages so they're being autoreleased. After every imageNamed call, you need a retain i.e.

baby = [[UIImage imageNamed:@"baby.png"] retain];

or, if you've declared them as properties (i.e. @property (nonatomic, retain) UIImage *baby;) you can do this :

self.baby = [UIImage imageNamed:@"baby.png"];

which is the more correct way to do it.


However, a better way of dealing with all this code might be to use an array of images instead of checking for the name each time. i.e.

imageArray = [NSArray alloc] initWithObjects:
              [UIImage imageNamed:@"Anvil.png"],
              [UIImage imageNamed:@"Apple.png"],
              [UIImage imageNamed:@"Arrow.png"],
              nil];

and then, when an item is selected,

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    [object setImage:[imagearray objectAtIndex:row]];
 }

which is a little cleaner ;)

EDIT: Douglas has had the same idea for cleaning up the code while I was writing the second half of my answer :)

Is the ninth object the only one with a space in the name? I don't see how that could break it, looking for differences between it and the others. The image isn't called "bungee jumper.png" instead of "bungeejumper.png" is it?

Aside: instead of a list of strings, you could have a list of image title pairs Eg,

// ... snip ...
[self addPairWithTitle:@"Anvil" image:@"anvil.png"];
[self addPairWithTitle:@"Apple" image:@"apple.png"];

- (void) addPairWithTitle .... 
{
    // you'll need to define a MyNewPair object which retains the image and title
    [list addObject:[[MyNewPair alloc] initWithTitle:title andImage:[UIImage imageNamed:imageName]];
}

// ... snip ...

... titleForRow...
return [[list objectAtIndex:row] title];

...didSelectRow...
[object setImage:[[list objectAtIndex:row]] image];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!