Shiun
Shiun

Reputation: 2677

Can't have an ivar with a name of description in Objective-C description method?

I'm trying to implement the Objective-C description method for my NSObject-derived object.

However, my derived object has an ivar of name description. And for some reason this is causing a crash.

- (NSString *) description {

    NSMutableString *output = [NSMutableString string];
    [output appendFormat:@"MyObject.description = %@\n", self.description];

    return output;
}

Why would this be an issue?

Upvotes: 1

Views: 114

Answers (2)

NSGod
NSGod

Reputation: 22948

It's an issue because you're creating an infinite loop. self.description will call [self description], which is exactly the method you're within. Hence you have the method calling itself repeatedly.

- (NSString *) description {

    NSMutableString *output = [NSMutableString string];
    [output appendFormat:@"super's description = %@\n", [super description]];
    [output appendFormat:@"MyObject.description = %@\n", description];

    return output;
}

You can access the instance variable directly, rather than using self.description. Also, I added an extra line to show how you can call super's description method (which doesn't create an infinite loop).

Upvotes: 1

James Eichele
James Eichele

Reputation: 119164

Short Answer: The crash is a result of a stack overflow because your -description method calls itself repeatedly. To do what you want to do (accessing the ivar from within the description method), you should not use the prefix self. in front of the ivar.

More Detail:

In Objective-C, self.description is shorthand for [self description]. Using the dot-syntax informs the compiler that you want to access a property named description, and not the ivar itself.

Upvotes: 5

Related Questions