0

I have some trouble logging custom objects.

An Example with a DateObject Class:

Header

@interface DateObject : NSObject {

    NSString *month;
    NSString *day;
    NSString *year;
}
@property (nonatomic, retain)NSString *month;
@property (nonatomic, retain)NSString *day;
@property (nonatomic, retain)NSString *year;
- (NSString *)description;

Implementation:

#import "DateObject.h"

@implementation DateObject
@synthesize month, day, year;

- (NSString *)description{
    NSString *result = [NSString stringWithFormat:@"{\n\tMonth:\t%@\n\tDay:\t%@\n\tYear:\t%@\n}",self.month, self.day, self.year];
    return result;
}

@end

Now I set the Values like this:

DateObject *date = [[[DateObject alloc] init] autorelease];
date.month       = @"Mar";
date.day         = @"04";
date.year        = @"2013";

Logging the Object with this

NSLog(@"{\n\tMonth:\t%@\n\tDay:\t%@\n\tYear:\t%@\n}",date.month, date.day, date.year);

results (as expected) in

2013-03-04 10:42:08.821 LoggingCustomObjectsExample[4389:c07] {
    Month:  Mar
    Day:    04
    Year:   2013
}

Now trying to log the object with

NSLog(@"%@", date);

I expect my description method to get called (it actually does get called), but the result always is unformatted:

2013-03-04 10:59:18.835 LoggingCustomObjectsExample[4389:c07] DateObject: "{\n\tMonth:\tMar\n\tDay:\t04\n\tYear:2013}";

I dont understand why the escape sequences are not working here. Am I missing something?

pmk
  • 1,897
  • 2
  • 21
  • 34

1 Answers1

2

This is known behaviour of NSLog and it's escaping those newline and tab characters so the output remains on a single line (see this SO question).

I would say that you don't want newline characters in your description output anyway, as they add no value.

Community
  • 1
  • 1
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • Thanks for your quick reply, I did not know this was a known behaviour. I just thought it would have been nice to have a formatted log like logging an NSArray – pmk Mar 04 '13 at 10:16
  • You probably still can, just not using `NSLog()`. (I don't use `NSLog()` in production code anyway, and rely on my own logging code). – trojanfoe Mar 04 '13 at 10:19
  • May I ask why you dont use NSLog()? I have been using NSLog() all the time... Is this bad in any way? – pmk Mar 04 '13 at 10:23
  • I don't use `NSLog()` because I write my logging data to file, so I can optionally upload them somewhere or get the user to send them to me for post-mortem debugging. My logging code also provides logging levels with runtime support to turn off verbose debug-level messages, which are generally only useful to me during development. – trojanfoe Mar 04 '13 at 10:26