How to create a NSArray of unknown NSStrings?
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]]
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]
.
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);
}
}
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
精彩评论