0

My code is as follows:

NSString *str1 = @"Name";
NSString *str2 = @"Age";

NSArray *array = [[NSArray alloc] initWithObjects: str1, str2 count:2];

However when I Build & Run I get an exception thrown which says: Expected ':' right before the 'c' in count.

Why is this? I've tried inputting the ':' though I know that's syntactically incorrect and then Xcode asks me to close off with a ']' before count.

deleted_user
  • 3,817
  • 1
  • 18
  • 27
Ryan
  • 767
  • 3
  • 9
  • 31

2 Answers2

4

initWithObjects:count: is for use with C arrays. In your case, you'll want to use initWithObjects: with a nil argument at the end:

NSString *str1 = @"Name";
NSString *str2 = @"Age";

NSArray *array = [[NSArray alloc] initWithObjects: str1, str2, nil];
Codo
  • 75,595
  • 17
  • 168
  • 206
3

If you just started learning Objective-C, just use the most convenient methods introduced recently:

NSArray* array= @[ str1, str2] ;

For more details, see What are the details of "Objective-C Literals" mentioned in the Xcode 4.4 release notes?

Community
  • 1
  • 1
Yuji
  • 34,103
  • 3
  • 70
  • 88
  • Yea I'm aware of this literal, however I want to understand the underlying mechanics of what I'm doing before I start shortcutting. Great suggestion though. – Ryan Oct 23 '12 at 15:18
  • Great. Note that the literal is turned by the compiler into a call to `+[NSArray initWithObjects:count]` which you tried originally. See http://clang.llvm.org/docs/ObjectiveCLiterals.html – Yuji Oct 23 '12 at 15:21