Reputation: 16051
I'm trying to add objects to this NSArray (labelArray) but for some reason, it returns as (null) in NSLog every time, and the count remains at 0.
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(howFarAlong, howFarDown, 50, 70)];
label.text = @"text";
[self.view addSubview:label];
[labelArray addObject:label];
NSLog(@"%@", labelArray);
[label release];
Upvotes: 2
Views: 2285
Reputation: 2233
I tested the code below. The count is 1 after the lable is added.
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(howFarAlong, howFarDown, 50, 70)];
label.text = @"text";
[self.view addSubview:label];
NSArray *labelArray = [NSArray arrayWithObject:label];
NSLog(@"Count: %d", labelArray.count);
Upvotes: 0
Reputation: 1850
You need to use an NSMutableArray if you want to change the data in your array. NSArray can only be used to create static arrays.
Upvotes: 2
Reputation: 12979
You probably also receive a message from the compiler stating that NSArray may not respond to 'addObjext'. This is your clue that the object you are using won't perform the requested selector (method). In this case, you are trying to change an immutable object, which won't work. You need to use an NSMutableArray. I suggest you read up on the differences in Apple's documentation.
Upvotes: 0
Reputation: 19071
An NSArray
is immutable. If you want to call -addObject:
, use NSMutableArray
. If labelArray
is an NSArray
, then that should crash. If it doesn’t crash, then it’s probably nil
, and you haven’t initialized it. Some code that will work:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(howFarAlong, howFarDown, 50, 70)];
label.text = @"text";
[self.view addSubview:label];
if (labelArray == nil) {
labelArray = [[NSMutableArray alloc] init];
}
[labelArray addObject:label];
NSLog(@"%@", labelArray);
[label release];
Upvotes: 12