Reputation: 2259
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!
Upvotes: 0
Views: 295
Reputation: 15861
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.
Upvotes: 4
Reputation: 104082
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.
Upvotes: 2