Custom NSLog Method (Variadic)

I am trying to create my own NSLog() DNSLog() NSLog() method, which only executes NSLog if the debug variable is correct.

 -(void)DNSLog:(NSString *)formatString, ... { if(debug){ va_list args; va_start(args, formatString); NSLog([[NSString alloc] initWithFormat:formatString arguments:args]); va_end(args); } } 

But when I try to call using

 DNSLog(@"Hello %d",x); 

I get a compilation error:

 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) 

I used this as a link: http://www.cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html

Where am I going wrong?

+6
source share
3 answers

You have confusing methods and functions - Objective-C has both. NSLog is a standard function, so you call it NSLog(...) . You have defined a method:

 -(void)DNSLog:(NSString *)formatString, ... 

but tried to call it a function. To call your method, you need to do:

 [self DNSLog:@"Hello %d", x]; 

Since your code is compiling, you must have a global or instance debug variable. If it is global, you can define DNSLog as a function (this will not work if debug is an instance variable, since only those methods can access them directly). The function will start:

  void DNSLog(NSString *formatString, ...) 

The body of the function will be the same as for the method.

NSLog also has the NS_FORMAT_FUNCTION attribute to tell the compiler that it takes a format string as an argument, seeing this, the compiler checks the string and format arguments to make sure they match. To do this for your method or function, write:

 -(void)DNSLog:(NSString *)formatString, ... NS_FORMAT_FUNCTION(1,2); 

or

 void DNSLog(NSString *formatString, ...) NS_FORMAT_FUNCTION(1,2); 

in an interface or header file.

NTN.

+14
source

Instead of using a custom method, try adding this macro to your application, possibly to your .pch file.

 #ifdef DEBUG #define MyLog(x, ...) NSLog(@"%s %d: " x, __FUNCTION__, __LINE__, ##__VA_ARGS__) #else #define MyLog(x, ...) #endif 

This will start the user log, which I call MyLog in debug mode, and when it is released, it will do nothing. It also prints other useful information, such as file number and log lines.

+12
source

Thanks to everyone for your extremely "valuable", "encouraging" and "supportive" answers to the newbie.

I found my error, and here is the corrected working code:

 void ZNSLog(NSString *format, ...){ if(!ENABLE_DEBUGGING) return; va_list args; va_start(args, format); NSLogv(format, args); va_end(args); } ZNSLog(@"Hello"); 

The previous method I used was Objective-C method

 -(void)DNSLog:(NSString *)formatString, ... 

which I tried to call using a function call C.

+9
source

Source: https://habr.com/ru/post/946645/


All Articles