简体   繁体   中英

Can't get addObject to work on NSMutableArray

I am trying to add UIButton objects to an array, but they fail to do so. Whenever I call [pixels count] or [colors count] it returns 0. I tried using [self.arrayName addObject:myObject] and [arrayName addObject:myObject] but neither seem to work. I'm pretty new to Objective-C so it probably seems dumb on my part, but this has been stumping me for over an hour.

Here is the code for ViewController.h

 #import <UIKit/UIKit.h>

 @interface ViewController : UIViewController {
 NSMutableArray *pixels;
 NSMutableArray *colors;
 }
 @property (nonatomic, retain) NSMutableArray *pixels;
 @property (nonatomic, retain) NSMutableArray *colors;
 @end

And here is the relevant code from ViewController.m

 int x = 30;
 int y = 60;
 for(int i=0; i<10; i++ ) {
      UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
      [self.pixels addObject:button];
      x += 20;
      y += 20;
 }

I have the whole project zipped up which can be downloaded here: http://mdl.fm/pixelated.zip

Thanks in advance to anyone who can help!

Try adding this in before you try to use the arrays:

NSMutableArray *pixels = [[NSMutableArray alloc] init];

Arrays in Obj-C need to be initialized before being used. Since calling methods on a nil instance just returns zero in Obj-C, it's easy to do this and not notice until your array isn't storing what you think it should.

Edit to add info from comments:

You can put the initialization into the -ViewDidLoad method, so that they are ready to go once the ViewController itself is ready. Make sure you retain them, so they don't get automatically garbage-collected.

You initialized pixels in an init method -- init is not called for a controller you set up in a storyboard. Either change that to initWithCoder: or move your array initializations to viewDidLoad.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM