Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro with ## in @interface, what does it mean?

What does it do, especially the ## ?

#define CUSTOM_ARRAY_INTERFACE(classname) \
@interface classname ## Array : ConcreteMutableArray \
- (void) add:(classname*)obj;\
- (classname*) get:(int)index;\
@end\

What does CUSTOM_ARRAY_INTERFACE(NSString) generate then, this idea of mine doesn't even work

@interface NSString ## Array : ConcreteMutableArray
- (void) add:(classname*)obj;
- (classname*) get:(int)index;
@end

?

Is a way to show to what code a macro would get expanded, without looking into assembler code?

like image 569
Binarian Avatar asked Sep 26 '13 13:09

Binarian


1 Answers

The ## is a macro concatenation operator, so that

CUSTOM_ARRAY_INTERFACE(Foo)

would concatenate Foo with Array and result in

@interface FooArray : ConcreteMutableArray 
- (void) add:(Foo*)obj;
- (Foo*) get:(int)index;
@end

Or

CUSTOM_ARRAY_INTERFACE(NSString)

would result in

@interface NSStringArray : ConcreteMutableArray 
- (void) add:(NSString*)obj;
- (NSString*) get:(int)index;
@end

It's worth noting that Objective-C now supports lightweight generics, eliminating the need for the above pattern. For example, NSArray lets you specify the type of objects for the individual elements in the array, e.g.

NSArray <NSString *> *array = ...

Now the compiler knows that array is an array of strings without needing to declare a specific type for this. The compiler will know that the following is valid:

NSString *string = array[0];

But if you attempted to do something like:

NSNumber *number = array[0];

It would resulting in the following compile-time warning:

Incompatible pointer types initializing 'NSNumber *' with an expression of type 'NSString *'.

Note, this is a "lightweight" generic. E.g. it merely results in compile-time warnings, but doesn't strictly enforce this at runtime like true generics in other languages (such as Swift).

like image 184
Rob Avatar answered Oct 15 '22 09:10

Rob