UIPickerView EXC BAD ACCESS?

后端 未结 2 1962
臣服心动
臣服心动 2021-01-14 17:38

I keep getting a exc bad access error and I think it has something to do with my UIPickerView because this is when the app crashes. Everything works fine until I make a 9th

2条回答
  •  猫巷女王i
    2021-01-14 18:17

    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 :)

提交回复
热议问题