Search code examples
iosobjective-cuiimageviewuiimagensarray

Adding UIImageView into NSArray crashing


I would like to know how to add a UIImageView into an NSArray without it crashing.

Currently I am doing this.

//.h
@property (strong, nonatomic) UIImageView *transButtonImageView;
@property (strong, nonatomic) UIImage *transButtonImage;

//.m
@synthesize transButtonImageView;
@synthesize transButtonImage;

transButtonImage = [UIImage imageNamed:@"trans.png"];
[transButtonImageView setImage:transButtonImage];

 NSMutableArray *arrayOfButtonImages = [[NSMutableArray alloc] init];
[arrayOfButtonImages addObject:transButtonImageView]; // this is where the error happens

When I try to add transButtonImageView to the NSArray if I look at the value of the imageView it's set at nil, even though I have added the image?


Solution

  • There is no crash log, so the error may come from any where, but the following are the possible ones:

    1. Does the UIImageView initialise? As we know, nil is equal to the NSInteger 0, is not an object, so when nil is added into any container, there will be a crash;

    2. Is the container initialised with capacity? We can only add or remove object from Mutable containers, it must be a NSMutableArray with capacity.

    3. May the image is too large, which hold a high memory, cause the memory warning.

    You'd better try all the above. Good luck!