Question

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]))];
}
Was it helpful?

Solution

@[] 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

OTHER TIPS

@[] 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))];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top