2

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];
2
  • 1
    Can you show the code where you init your NSMutableArray *labelArray? Commented Feb 24, 2011 at 21:01
  • not xcode-related. check for the usage of the tag [xcode]: stackoverflow.com/tags/xcode/info Commented Feb 24, 2011 at 23:38

4 Answers 4

12

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];
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.