Search code examples
objective-cnslog

How do i convert NSLog to string?


I have the following code,

#define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);

How do I convert NSLog output to a string so i can pass into log parameter? see below.

#define DLog(fmt, ...) [MyClass log:NSLogString];

Solution

  • You can't "...convert NSLog output to a string". NSLog sends its output to standard output. It does a file operation.

    You should be able to use code like this:

    void DLog(NSString* format, ...)
    {
        va_list params_list;
    
        //Extract the variable-length list of parameters
        va_start(params_list, format);
    
        NSString *outputString = [[NSString alloc] initWithFormat: format 
          arguments: params_list];
    
        //Now do what you want with your outputString
    
        //Now clean up the var_args.
        va_end(params_list);
    }
    

    The magic is the NSString initWithFormat:arguments: method, which takes a params_list extracted from var_args and returns a string. That's what you want.