What's the easiest / fastest way to initialize an array of NSString
s in Objective C?
Asked
Active
Viewed 7.0k times
47

Alexander Abakumov
- 13,617
- 16
- 88
- 129

user680406
- 5,637
- 6
- 24
- 19
4 Answers
73
NSArray *array = [NSArray arrayWithObjects:@"String1",@"String2",@"String3",nil];

Tomas McGuinness
- 7,651
- 3
- 28
- 40
-
Can I get rid of nil in the end ? I guess not, but why do I have to add it in the end ? – user680406 May 05 '11 at 15:48
-
1This just indicates that you have no more elements to add. It's a kind of null terminator I guess. – Tomas McGuinness May 05 '11 at 15:49
-
15@user680406: A function or method with a variable number of arguments doesn't have any way of knowing how many arguments you passed to it (this is just a limitation of the C programming language). So, since NSArray can't contain `nil` anyway, it interprets `nil` as part of a variable argument list to mean "OK, that's all the arguments." This is called a "sentinel value." Without nil to tell it where the arguments end, it wouldn't know any better than to keep walking through memory, trying to treat everything it encounters as an object to be added to the array, until it encountered a 0 or nil. – Chuck May 05 '11 at 17:52
40
C way:
NSString *s1, *s2; NSString *cArray[]={s1, s2};
The size of the cArray is 2, defined by the compiler.
More info here: How to initialize all members of an array to the same value?NSArray (Objective-C) way:
NSArray *objCArray = [NSArray arrayWithObjects:@"1", @"2", nil];
If you are using XCode4 (LLVM4.0 compiler), now you can use NSArray literals:
NSArray *array = @[ @"1", @"2" ];
More info here: What are the details of "Objective-C Literals" mentioned in the Xcode 4.4 release notes?
4
NSString *stringArray[2] = {@"1", @"2"};

Kai Huppmann
- 10,705
- 6
- 47
- 78
-
So, if I specify the size I don't need to add nil in the end ? Why ? – user680406 May 05 '11 at 15:48
-
4The previous answer is for an NSArray, this is for a C array. These are *completely* different, and understanding the difference is pretty much a requirement for objective-c programming. – Catfish_Man May 05 '11 at 16:41
-
Storing objects in a C array is an even iffier proposition than C arrays are in the first place, and that's saying something. – Chuck May 05 '11 at 17:57
-
Telling a newbie developer to create C arrays of NSObjects is very bad advice. The ONLY way this works properly is with string constants created with a string literal like `@"someString"`. – Duncan C Oct 07 '16 at 01:46
-
If you tried to do this with dynamically allocated `NSString` objects in ARC then the C array would not hold a strong reference to the strings and they would get deallocated when the last strong reference to them went out of scope and the C array would be an array of invalid memory addresses. (An array of "zombies") – Duncan C Oct 07 '16 at 01:47