Kyu*_*ubi 6 string objective-c variadic-functions ios ios6
我正在尝试创建一个自定义NSLog()
方法,只有在调试变量为true时才DNSLog()
执行该方法NSLog
.
-(void)DNSLog:(NSString *)formatString, ...
{
if(debug){
va_list args;
va_start(args, formatString);
NSLog([[NSString alloc] initWithFormat:formatString arguments:args]);
va_end(args);
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用它时
DNSLog(@"Hello %d",x);
Run Code Online (Sandbox Code Playgroud)
我收到一个编译错误:
Undefined symbols for architecture i386:
"_DZNSLog", referenced from:
-[RestaurantInfoViewController viewDidLoad] in RestaurantInfoViewController.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Run Code Online (Sandbox Code Playgroud)
我用这个作为参考:http://www.cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html
我哪里错了?
CRD*_*CRD 14
你有混淆的方法和功能 - Objective-C有两个.NSLog
是一个标准函数,所以你称之为NSLog(...)
.您已定义了一个方法:
-(void)DNSLog:(NSString *)formatString, ...
Run Code Online (Sandbox Code Playgroud)
但试图将其称为功能.要调用您的方法,您需要执行以下操作:
[self DNSLog:@"Hello %d", x];
Run Code Online (Sandbox Code Playgroud)
在编译代码时,您必须具有全局debug
变量或实例变量.如果它是全局的那么你可以定义DNSLog
为一个函数(如果debug
是一个实例变量,这将不起作用,因为只有方法可以直接访问它们).该功能将开始:
void DNSLog(NSString *formatString, ...)
Run Code Online (Sandbox Code Playgroud)
函数的主体将与方法相同.
NSLog
还有一个属性,NS_FORMAT_FUNCTION
在其上告诉编译器它将格式字符串作为参数,看到这一点,编译器将检查格式字符串和参数以查看它们是否匹配.为您的方法或函数执行此操作:
-(void)DNSLog:(NSString *)formatString, ... NS_FORMAT_FUNCTION(1,2);
Run Code Online (Sandbox Code Playgroud)
要么:
void DNSLog(NSString *formatString, ...) NS_FORMAT_FUNCTION(1,2);
Run Code Online (Sandbox Code Playgroud)
在接口或头文件中.
HTH.
Eri*_*ric 12
不要使用自定义方法,请尝试将此宏添加到您的应用中,可能在.pch文件中.
#ifdef DEBUG
#define MyLog(x, ...) NSLog(@"%s %d: " x, __FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define MyLog(x, ...)
#endif
Run Code Online (Sandbox Code Playgroud)
这将运行我在调试模式下调用MyLog的自定义日志,并且在发布时,它不会执行任何操作.它还会打印出一些其他有用的信息,例如日志的文件和行号.
Kyu*_*ubi 11
感谢大家对初学者的极为"有价值","鼓励"和"支持"的答案.
我发现了我的错误,这是更正的工作代码:
void ZNSLog(NSString *format, ...){
if(!ENABLE_DEBUGGING)
return;
va_list args;
va_start(args, format);
NSLogv(format, args);
va_end(args);
}
ZNSLog(@"Hello");
Run Code Online (Sandbox Code Playgroud)
我之前使用的方法是Objective C方法
-(void)DNSLog:(NSString *)formatString, ...
Run Code Online (Sandbox Code Playgroud)
我试图使用C函数调用调用.
归档时间: |
|
查看次数: |
6742 次 |
最近记录: |