【问题标题】:How to Print out(NSLog) the properties of a custom object added to a NSMutableArray如何打印(NSLog)添加到 NSMutableArray 的自定义对象的属性
【发布时间】:2013-10-12 23:57:12
【问题描述】:

我创建了一个自定义对象,其中定义了 3 个属性。我创建对象并将值分配给这些属性。之后,我将该对象放入NSMutable Array。我知道我可以使用:

for (id obj in personArray)
{
             NSLog(@"obj: %@", obj);
}
NSLog(@"%@", personArray);

告诉我数组中有哪些类型的对象。但我想更深入地了解每个对象的属性。我只是不确定如何定位他们。

这是代码,我正在使用: Person 是我的自定义对象。

personObject = [[Person alloc]init];
[personObject setFirstName:firstName.text];
[personObject setLastName:lastName.text];
[personObject setEmail:emailAddress.text];

// add the person object to the array
// the array was alloc and init in a method above this code.
[personArray addObject:personObject];

for (id obj in personArray)
{
    NSLog(@"obj: %@", obj);
}

NSLog(@"%@", personArray);

【问题讨论】:

  • 别忘了把解决你的问题的答案标记为已解决。
  • 是的,为该类编写一个description 方法。
  • 在我的 XCode 5.1 下载详细信息“在调试器中为自定义对象类型添加快速查看支持”中看到了这个注释。手指交叉,这就是我所希望的。立即下载。
  • 顺便说一句,我所做的是生成一个包含所有属性的 NSDictionary,然后返回其中的 description 或返回其 JSON 序列化。

标签: ios objective-c nsmutablearray


【解决方案1】:

你必须在你的 Person 类中使用 description 方法

-(NSString *)description{

    return @"FirstName: %@, LastName: %@, E-mail: %@", 
                        _firstName, _lastName, _email;
}

通过这种方式,您可以始终打印您在 NSArray 中的对象,但您将得到返回的不是内存描述,而是您之前在特定对象的描述方法中定义的值。

如果您只想对 NSArray 中的元素执行此操作,请使用占位符:

NSLog(@"FirstName: %@, LastName: %@, E-mail: %@", 
                       obj.firstname, obj.lastname, obj.email);

两者之间没有太大区别,但它更有用,因为一旦创建了描述方法就不必重写它,只需打印对象即可。

【讨论】:

    【解决方案2】:

    有一个比在所有类中都使用描述方法更简单的方法。

    使用 ICHObjectPrinter:

    NSLog(@"Object description is %@",[ICHObjectPrinter descriptionForObject:person]);
    

    https://github.com/arundevma/ICHObjectPrinter

    【讨论】:

      【解决方案3】:

      要打印一个对象的所有属性,请使用以下代码:

      - (void) logProperties:(NSObject*)obj {
      
      NSLog(@"----------------------------------------------- Properties for object %@", obj);
      
          unsigned int numberOfProperties = 0;
          objc_property_t *propertyArray = class_copyPropertyList([obj class], &numberOfProperties);
          for (NSUInteger i = 0; i < numberOfProperties; i++) {
              objc_property_t property = propertyArray[i];
              NSString *name = [[NSString alloc] initWithUTF8String:property_getName(property)];
              NSLog(@"Property %@ Value: %@", name, [self valueForKey:name]);
          }
      NSLog(@"-----------------------------------------------");
      }
      

      【讨论】:

        【解决方案4】:

        如需更高级的解决方案,请查看此答案https://stackoverflow.com/a/2304797/519280。您可以将此代码添加到您的 Person 对象扩展的基类中,然后您可以使用 autoDescribe 函数自动打印出您的对象的所有属性,而无需通过手动列出所有属性的过程描述方法。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-12-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多