-3

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
HurkNburkS
  • 5,492
  • 19
  • 100
  • 183
  • 5
    1) You must know by now that you when posting a question about an error you need to post what the actual error is. 2) Have you verified whether `transButtonImageView` is `nil` or not? – rmaddy Jul 22 '14 at 00:13
  • Well when I say error, it just crashes the only reason I caught it because I used an All Exceptions breakpoint.. and it just shows the "Thread 1: breakpoint 1.1" where its crashing. I used poor wording sorry. – HurkNburkS Jul 22 '14 at 00:46
  • 2
    Did you ever create the image view? I don't see it in your code. – rdelmar Jul 22 '14 at 00:51
  • Yeah, like @rdelmar said, you never initialized transButtonImageView, so you're adding "nil" to arrayOfButtonImages which should raise an NSInvalidArgumentException. – Lyndsey Scott Jul 22 '14 at 01:17
  • To see the error message, you must press "Continue" several times after hitting the initial exception breakpoint. But before then you need to make note of where the exception occurred. Or [add logic to your main to dump the exception stack](http://stackoverflow.com/a/12268397/581994). – Hot Licks Jul 22 '14 at 01:33

2 Answers2

2

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!

ccjmne
  • 9,333
  • 3
  • 47
  • 62
Niu Sir
  • 44
  • 1
  • okay I am going to try using **transButtonImageView = [[UIImageView alloc] initWithImage:transButtonImage];** – HurkNburkS Jul 22 '14 at 00:52
0

You need to use an NSMutableArray to be able to modify it. You can then use [mutableArray copy] to copy it to an NSArray.

WillyCornbread
  • 837
  • 1
  • 12
  • 21