Andrew
Andrew

Reputation: 16051

Why is this NSArray not working? I'm trying to add objects to it

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

Answers (4)

Ali
Ali

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

MiKL
MiKL

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

FreeAsInBeer
FreeAsInBeer

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

Jeff Kelley
Jeff Kelley

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

Related Questions