How can I get the numbers of elements in a macro definition like this:
#define myThings @"A",@"B",@"C",@"D",@"E"
What is the way to get the answer 5 from myThings?
[myThings count]
does not work...
How can I get the numbers of elements in a macro definition like this:
#define myThings @"A",@"B",@"C",@"D",@"E"
What is the way to get the answer 5 from myThings?
[myThings count]
does not work...
Defines are literal substitution of text: would it work a code like
[@"A", @"B", @"C" count];
? If the answer is no, it won't work, then here it is your problem. You could do
[[NSArray arrayWithObjects: myThings, nil] count];
This should work, but I do not suggest to use this "pattern" at all.
ADD
Another way to count how many values there are, could be the following:
NSString *arr[] = {myThings};
size_t cnt = sizeof(arr)/sizeof(NSString *);
this is a C common way to know how many elements are in arr
. Again, I stress the fact that myThings
is literally replaced by whatever you defined it using #define
, and so the result is the same as
NSString *arr[] = {@"A", @"B", @"C", @"D", @"E"};
Add2
Note that, if you won't use arr
"for real", optimizations will remove it, and there's no "waste of space".
However, another solution would be to count the number of arguments passed to a macro, so that CountingMacro(myThings) would be replaced with 5. This SO answer might help in this case.