1

NSArray 的 -description 方法将嵌套递归调用,如下所示:

2009-05-15 14:28:09.998 TestGUIProject[29695:813] (
    a, // Array1 item 1
        ( // Array2, a second array, nicely indented another 4 spaces
        a // Item in Array2
    ) // End of Array2
) // End of Array1

我想为我自己的自定义类做类似的事情(使用我正在编写的脚本)。

我不知道当递归调用的对象添加自己的新行时如何添加额外的缩进级别。

我所拥有的是以下内容:

- (NSString *)description {
    return [NSString stringWithFormat:@"{{{\n"
            @"    prop1: %@\n"
            @"    prop2: %@\n"
            @"    prop3: %@\n"
            @"    prop4: %@\n"
            @"}}}",
            self.prop1,
            self.prop2,
            self.prop3,
            self.prop4];
}

但是,一旦其中一个属性是 NSArray 或使用相同描述格式的另一个对象,这就会崩溃,因为它不能很好地嵌套。

相反,您会得到:

2009-05-15 14:25:50.899 TestApp[29636:813] {{{
    prop1: SomeValue1
    prop2: ( // Prop 2 is an Array of strings
    "String1", // Note no additional level of indentation as in the NSArray example
    "String2",
    "String3",
    "String4"
)
    prop3: SomeValue3
    prop4: SomeValue4
}}}

如何获得额外的嵌套级别?

4

3 回答 3

8

你想要的是这个函数,在 NSArray 和 NSDictionary 上可用:

- (NSString *) descriptionWithLocale: (id) locale indent: (NSUInteger) level;

指定缩进 1 以使嵌套数组或字典将其打印的所有内容缩进指定数量。

于 2009-05-15T22:59:32.413 回答
1

这实际上适用于我的目的:

[[self.prop2 description] stringByReplacingOccurrencesOfString:@"\n" withString:@"\n    "]
于 2009-05-15T22:24:18.333 回答
0

您可能不得不放弃依赖descriptionin NSArray。也许您应该编写一个方法来遍历数组并在添加到NSString. 您可能必须使用 anNSMutableString并传递它,以便可以将字符串附加到它。

编辑

根据您的评论,我会说使用这些objc_*方法来反映已传递给您的调试方法的任何对象。从那里您可以提取所有属性或实例变量并遍历它们。您还可以使用条件来检查 ivar 的类型,如果它是标准集合类,例如NSArrayor NSDictionary,则自己对其进行迭代以以您想要的格式输出数据(然后当然处理其他类型的对象和所有原语以自己的方式)。

于 2009-05-15T21:49:01.663 回答