Error in output lead to question about description method


#1

Hi,
after working through chapter 19 Object Instance Variables
following line in main

NSLog(@"Employees: %@", employees);
prints that output:
Employees: (
"<Employee: 0x10a5147b0>",
"<Employee: 0x10a5148b0>",
"<Employee: 0x10a5148f0>",
"<Employee: 0x10a514930>",
"<Employee: 0x10a514950>",
"<Employee: 0x10a514910>",
"<Employee: 0x10a5149a0>",
"<Employee: 0x10a514a10>",
"<Employee: 0x10a514a30>",
"<Employee: 0x10a514a50>"
)

Not quite the same like in the book. I got 10 addresses to Employee objects. Hhm…?
After revisiting my code I found I forgot to implement the overridden description method. I added that. Output now OK like in the book:

Employees: (
"<Employee 0: $0 in assets",
"<Employee 1: $153 in assets",
"<Employee 2: $119 in assets",
"<Employee 3: $68 in assets",
"<Employee 4: $0 in assets",
"<Employee 5: $136 in assets",
"<Employee 6: $119 in assets",
"<Employee 7: $34 in assets",
"<Employee 8: $0 in assets",
"<Employee 9: $136 in assets"
)

But how was that overridden description method called/invoked?

appreciate your help, merci
Matthias


#2

NSLog can be described abstractly as NSLog (format-string argument-list).

While scanning its format string, if and when NSLog encounters the %@ directive it calls the description method on the corresponding argument in the argument list. This implies that that argument has to be an instance of an object. And all standard objects inherit from the NSObject which declares the description method and also provides a default implementation for it. If that implementation is overridden by a class and an instance of it appears in the argument list, then the description method of that object is invoked.


#3

ibex10: Nailed it.

Matthias: As an experiment in further understanding what’s going on, try using the %@ substitution token in a format string, but passing a primitive variable (an int, double, etc.) and see what happens. What behavior do you get? Why?


#4

Merci to ibex10 and MikeyWard

I get an EXC_BAD_ACCESS...
Why? The %@ substitution token is expecting an address to an object somewhere on the heap but only gets a primitive variable.