2

It's been a while since Clang added Objective-C literal syntax for NSDictionary, NSArray, NSNumber, and BOOL literals, like @[object1, object2,] or @{key : value}

I'm looking for the selector name associated with the array literal, @[].

I tried to find out using the following code for NSArray, but I didn't see a selector that seemed right.

 unsigned int methodCount = 0;
 Method * methods = class_copyMethodList([NSArray class], &methodCount);

 NSMutableArray * nameOfSelector = [NSMutableArray new];
 for (int i = 0 ; i < methodCount; i++) {
    [nameOfSelector addObject:NSStringFromSelector(method_getName(methods[i]))];
}
jscs
  • 63,694
  • 13
  • 151
  • 195
Hitesh Savaliya
  • 1,336
  • 13
  • 15

2 Answers2

9

@[] is not a method on NSArray, so you're not going to find it there.

The compiler just translates @[] into a call to [NSArray arrayWithObjects:count:]. As in it basically finds all the @[] and replaces it with [NSArray arrayWithObjects:count:] (carrying across the arguments of course)

See the Literals section here

Jonathan.
  • 53,997
  • 54
  • 186
  • 290
  • Actually, I suspect that some "internal" interface to NSArray is used. – Hot Licks May 04 '14 at 02:22
  • 4
    @HotLicks The [documentation](http://clang.llvm.org/docs/ObjectiveCLiterals.html) says that it expands to `+[NSArray arrayWithObjects:count:]`, as Jonathan reports. – Rob May 04 '14 at 02:23
  • @Rob - But most of the array and dictionary constructors are not what they seem. Different constructors would be used, eg, for an all-literal array vs one with dynamically created elements. – Hot Licks May 04 '14 at 02:39
  • 2
    The key thing is it is syntactic sugar. That means it's a convenience form to type but gets converted to something else. The precise constructors or class cluster objects used are generally irrelevant and intended to be treated as irrelevant. – uchuugaka May 04 '14 at 05:49
3

@[] uses +arrayWithObjects:count:

Official Clang Documentation

Array literal expressions expand to calls to +[NSArray arrayWithObjects:count:], which validates that all objects are non-nil. The variadic form, +[NSArray arrayWithObjects:] uses nil as an argument list terminator, which can lead to malformed array objects.

When you write this:

NSArray *array = @[ first, second, third ];

It expands to this:

id objects[] = { first, second, third };
NSArray *array = [NSArray arrayWithObjects:objects count:(sizeof(objects) / sizeof(id))];
Tricertops
  • 8,492
  • 1
  • 39
  • 41