tags:

views:

43

answers:

2

Does NSLog() have variants that print without the time and date stamps, and the automatic newline?

Thanks. Now with following code, I can print NSString, cString, or objects:

#import <Foundation/Foundation.h>
#import <stdio.h>

int main (int argc, const char * argv[]) {
  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

  NSString *s = @"Hello, World!";
  NSDate *today = [NSDate date];

  NSLog(@"%@", s);
  printf("%s at %s", [s UTF8String], [[today description] UTF8String]);

  [pool drain];
  return 0;
}  
+1  A: 

Use printf() instead of NSLog()

kuroutadori
Does printf() support NSString?
Stephen Hsu
@Stephen no, you would have to use something like `printf("%s %s\n", [someString UTF8String], [[someObject description] UTF8String]);`
cobbal
No, it's a C function. So you would have to convert NSString into a char array. So `printf([myString cStringUsingEncoding:NSASCIIStringEncoding]);`
kuroutadori
@kuroutadori you should really use a format string in case there's a `%`
cobbal
@cobbal good point, I forgot about that :P
kuroutadori
+1  A: 

It bothered me too, so I wrote a function to replace NSLog() and printf():

void IFPrint (NSString *format, ...) {
    va_list args;
    va_start(args, format);

    fputs([[[[NSString alloc] initWithFormat:format arguments:args] autorelease] UTF8String], stdout);

    va_end(args);
}

Then, you can just use it instead of NSLog() (e.g. IFPrint(@"Current date: %@", [NSDate date])), but it won't print out any timestamps or a newline, and you don't have to mess around with C strings and arrays, and whatnot. It's pretty handy, I'd say.

If you want, check out my full code (I've also written a replacement for fprintf, scanf, and fscanf) here.
(There's also an SO topic about it here).

itaiferber