views:

870

answers:

3

I have a very straight forward class with mostly NSString type properties. In it, I wrote a trivial implementation of the description method. I found that whenever I try to include "self" in the description, it crashes my iPhone app. An example is something such as the following:

- (NSString *)description
{
    NSString *result;

    result = [NSString stringWithFormat:@"me: %@\nsomeVar: %@", self, self.someVar];

    return result;
}

As soon as I remove the first parameter to the format string, self, it works as expected.

+2  A: 

You do realise that sets up an infinite recursion.

Your description implementation is implicitly calling itself when you pass in self, which then calls itself, and so on.

Your crash is mostly likely due to stack space running out... a "stackoverflow" if you will. Fitting considering the site :-)

freespace
+18  A: 

Use %p for self, then it will display the address of self. If you use %@, then it will call description on self, which will set up an infinite recursion.

dreamlax
+4  A: 

You can use [super description] instead of self to avoid the infinite recursion, like so:

- (NSString *)description
{
    return [NSString stringWithFormat:@"%@: %@", [super description], [self someVar]];
}
briankc