3

I have an object with two properties - type and name - which I want to show in its description. The out-of-the-box description looks like this:

<SGBMessage: 0x7663bb0>

If I override description, like so:

return [NSString stringWithFormat:@"<%@: %x type:%@ name%@>", 
           [self class], (int)self, self.type, self.name];

Then I can get a nice description like this:

<SGBMessage: 0x7663bb0 type:loadScreen name:mainScreen>

So far, so good. But Apple's objects have dynamic descriptions; if I look at a view's description I get this:

<UIView: 0x767bcb0; frame = (0 0; 0 0); layer = <CALayer: 0x767bd50>>

But if I set hidden to true, I get this:

<UIView: 0x767bcb0; frame = (0 0; 0 0); hidden = YES;
 layer = <CALayer: 0x767bd50>>

Now, I don't believe for a second that they've got a massive set of if statements in the description methods of all of their objects; it seems much more likely that there's some method in some category somewhere on NSObject that can be overridden to specify which properties show up in the description. Does anyone know what's really going on, and if so, is it something I can take advantage of?

4

1 回答 1

1

我的倾向于遵循这种模式:

- (NSString *) description {
    NSMutableDictionary *descriptionDict = [[NSMutableDictionary alloc]init];
    if (account)       [descriptionDict setObject:account       forKey:@"account"];
    if (date)          [descriptionDict setObject:date          forKey:@"date"];
    if (contentString) [descriptionDict setObject:contentString forKey:@"contentString"];
    return [descriptionDict description];
}

您可以使用类似的方法来构建一个NSMutableArray,然后遍历数组,将其中的内容添加到字符串中。

对于更复杂的应用程序,如果您有继承自其他类的自定义类,您还可以制作一个单独的方法返回descriptionDict,然后在子类中调用NSMutableDictionary *descriptionDict = [super descriptionDict]并继续向其添加/删除元素。

注意:我在每一行都使用if语句的原因是,如果一个对象恰好是nil,则会引发异常。当您尝试使用po您的对象时,这将导致“没有可用的客观 c 描述”打印出来。

但是要回答您的问题,没有秘密方法可以使某些属性出现在描述中。您只需要自己构建一个字符串,无论您决定采用何种合适的方式。

于 2012-12-20T22:29:17.063 回答