1

For example, I have @"John", @"Peter", ..., @"May" and need to construct NSArray:

 [@"John", @"Peter", ..., @"May"]

The number of NSString is unknown and is taking from an import text file. As NSArray does not support appending new element, how can I create NSArray?

Thanks

UPDATE, let me rephrase the question. How can I create the dynamic array paremeter required by the follow function call?

 [segmentedAttributes attributesWithTitlesArray:[NSArray arrayWithObjects:@"John", @"Peter", @"May", nil]]
4
  • 3
    At the risk of sounding like a n00b, what is the purpose/need for the nil? Commented May 4, 2011 at 4:09
  • 1
    NSArrays cannot contain nil. You could use NSNull, but why do you need it to be nil terminated? Commented May 4, 2011 at 4:10
  • Please see UPDATE about why. It seems my question is wrong :-( the nil is not actually needed. Commented May 4, 2011 at 4:19
  • No problem, never mind. That's how you learn things. Commented May 4, 2011 at 4:27

3 Answers 3

5

You don't.

You misunderstand the library behavior.

It is true that there is a convenience constructor arrayWithObjects: which is used thus:

NSArray* array=[NSArray arrayWithObjects:@"Low", @"Medium", @"High", nil];

But this does not create an array with nil at the end. This nil is just to signify the end of the variable-length argument list. It just creates an NSArray with three elements, not four with the last one nil.

You just need to create an NSArray containing the required elements, and pass it to the library function. For example:

NSMutableArray*array=[NSMutableArray array];
while(...){
    ... get a string ...
    [array addObject: string];
}

SCSegmentedAttributes*attributes=[SCSegmentedAttributes attributesWithSegmentTitlesArray:array];

should work, without adding a nil or [NSNull null].

Sign up to request clarification or add additional context in comments.

Comments

0

You can't store nil in a Foundation collection class. Instead, you can use [NSNull null]. Use an NSMutableArray, then when you want to add your 'nil' object, use [NSNull null].

Note that when you want to see if an object is [NSNull null] later on, that method will return the same instance every time, so you can do a direct point equality test, like this:

for (id anObject in myArray) {
    if (anObject == [NSNull null]) {
        NSLog(@"object is nil");
    }
    else {
        NSLog(@"object is not nil: %@", anObject);
    }
}

Comments

0

create mutable array then just use

NSString *myString = [NSString stringWithFormat:@"ur new string"];

[myArray addObject:myString];

you have to add object type to array when adding new abject in mutable array.

hope this will help

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.