47

What's the easiest / fastest way to initialize an array of NSStrings in Objective C?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
user680406
  • 5,637
  • 6
  • 24
  • 19

4 Answers4

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
  • 1
    This 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
Community
  • 1
  • 1
subzero
  • 3,420
  • 5
  • 31
  • 40
12

NSArray *array = @[@"foo",@"bar"];

Joel Martinez
  • 46,929
  • 26
  • 130
  • 185
jar_son
  • 117
  • 1
  • 3
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
  • 4
    The 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