在Objective-C描述方法中不能包含"self"?

Coo*_*coa 8 iphone cocoa cocoa-touch objective-c

我有一个非常直接的类,主要是NSString类型的属性.在其中,我写了一个描述方法的简单实现.我发现每当我尝试在描述中包含"self"时,它就会崩溃我的iPhone应用程序.一个例子是如下:

- (NSString *)description
{
    NSString *result;

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

    return result;
}
Run Code Online (Sandbox Code Playgroud)

一旦我将第一个参数删除到格式字符串self,它就会按预期工作.

dre*_*lax 30

使用%pself,那么它会显示的地址self.如果使用%@,那么它会调用descriptionself,这将建立一个无限递归.


bri*_*nkc 12

您可以使用[super description]而不是self来避免无限递归,如下所示:

- (NSString *)description
{
    return [NSString stringWithFormat:@"%@: %@", [super description], [self someVar]];
}
Run Code Online (Sandbox Code Playgroud)


fre*_*ace 6

您确实意识到设置无限递归.

description传入时self,您的实现隐式调用自身,然后调用自身,依此类推.

你的崩溃很可能是由于堆栈空间不足......如果你愿意,那就是"stackoverflow".考虑到网站的拟合:-)