2012-08-03 110 views
3

我試圖讓我的宏像接受可變參數的NSLog()一樣工作。下面的代碼導致解析問題。__VA_ARGS__宏擴展

什麼是定義這個的正確方法?

#define TF_CHECKPOINT(f, ...) \ 
do { \ 
NSString *s = [[NSString alloc] initWithFormat:f arguments:__VA_ARGS__] autorelease]; \ 
[TestFlight passCheckpoint:[NSString stringWithFormat:@"%@: %@", [self class], s]]; \ 
} while (0) 
+0

我不知道你怎麼個意思_variable arguments_因爲'__VA_ARGS__'已經代表了宏變量參數,這樣你就可以使用下面的宏,你會使用'的NSLog (...)'正常情況下:'#define AnotherLog(...)NSLog(__ VA_ARGS __)',之後它將成爲源代碼中的有效行:'AnotherLog(@「%d,%@」,1 ,@「text」);你最終的目標是什麼? – holex 2012-08-03 08:35:30

回答

7

您忘記了autorelease消息的左括號。

此外-[NSString initWithFormat:arguments:]預計va_list參數,而__VA_ARGS__被所有傳遞的參數替換。在這裏,您需要使用-[NSString initWithFormat:]+[NSString stringWithFormat:]

最後,您可以用##加上__VA_ARGS__的前綴。通過這樣做,當沒有參數時,前面的逗號被刪除。

試試這個:

#define TF_CHECKPOINT(f, ...) \ 
do { \ 
NSString *s = [NSString stringWithFormat:(f), ##__VA_ARGS__]; \ 
[TestFlight passCheckpoint:[NSString stringWithFormat:@"%@: %@", [self class], s]]; \ 
} while (0) 
+0

@Plenilune無論如何。 – trojanfoe 2012-08-03 08:19:33

+0

好吧,我忘記了左括號的愚蠢的錯誤。 – Morrowless 2012-08-03 08:24:59