【问题标题】:Can't include "self" in Objective-C description method?不能在 Objective-C 描述方法中包含“self”?
【发布时间】:2009-05-23 07:05:46
【问题描述】:

我有一个非常直接的类,其中大部分是 NSString 类型的属性。在其中,我编写了描述方法的简单实现。我发现每当我尝试在描述中包含“自我”时,它都会使我的 iPhone 应用程序崩溃。一个例子如下:

- (NSString *)description
{
    NSString *result;

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

    return result;
}

只要我删除格式字符串的第一个参数 self,它就会按预期工作。

【问题讨论】:

    标签: iphone objective-c cocoa cocoa-touch


    【解决方案1】:

    self 使用%p,则显示self 的地址。如果你使用%@,那么它会在self上调用description,这将设置一个无限递归。

    【讨论】:

      【解决方案2】:

      你可以用 [super description] 代替 self 来避免无限递归,像这样:

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

      【讨论】:

        【解决方案3】:

        您确实意识到这会设置无限递归。

        当您传入self 时,您的description 实现会隐式调用自己,然后它会调用自己,依此类推。

        您的崩溃很可能是由于堆栈空间耗尽......如果您愿意的话,一个“stackoverflow”。考虑到网站的拟合:-)

        【讨论】:

          猜你喜欢
          • 2013-07-15
          • 1970-01-01
          • 2013-01-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-18
          相关资源
          最近更新 更多