开发者

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

开发者 https://www.devze.com 2023-01-30 19:01 出处:网络
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.

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;
}

Wh开发者_StackOverflowy would this be an issue?


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.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消