What calls the method "-(NSString *) description"


#1

I understand that the method “-(NSString *) description” on p.53 makes the output be readable times and numbers. My difficulty is understanding what statement in main() calls this description method. Wouldn’t it be better to place this description directly in main()? There is something that I am missing. Any clarification would help.

Thanks in advance,

  • bobayres

#2

I was just wondering the same question.


#3

Just thought I’d follow up after reading the API Docs:

(NSString *)description essentially overrides the way NSStrings are displayed for the entire class. In our case, it was the LotteryEntry class that had the description redefined. I played around until I could understand this. This code (added to the bottom of main.m) shows the output for an NSString in the main class and the second NSString is from the LotteryEntry class.

[code]// main.m
LotteryEntry *test = [[LotteryEntry alloc]
[test setEntryDate:now];

// NSString that is not in LotteryEntry class
NSLog(@“NSString not in LotteryEntry class.”);
// NSString that is in LotteryEntry class
NSLog(@"%@", test);
[/code]

Output:

[quote]2012-04-29 13:57:59.506 lottery[25227:503] Jun 17, 2012 = 38 and 89
2012-04-29 13:57:59.507 lottery[25227:503] Jun 24, 2012 = 56 and 7
2012-04-29 13:57:59.509 lottery[25227:503] Jul 1, 2012 = 6 and 84
2012-04-29 13:57:59.509 lottery[25227:503] NSString not in LotteryEntry class.
2012-04-29 13:57:59.511 lottery[25227:503] Apr 29, 2012 = 0 and 0[/quote]


#4

When you use %@ in an Objective-C format string, such as with NSLog(), or +[NSString stringWithFormat:], the %@ means: “send the -description message to this object and insert the resulting string in my place.” This is the same sort of thing as %d and %f and so forth, except in those cases the formatter decides how to turn them into a string representation. In this case the object can decide how it will be represented.

The call to -description is made within NSLog() or +stringWithFormat:; you can check this by putting a breakpoint in -description and looking at the stack.

Adam