我创建了一个自定义对象,其中定义了3个属性。我创建对象并将值分配给这些属性。之后我将该对象放入NSMutable Array
。我知道我可以使用:
for (id obj in personArray)
{
NSLog(@"obj: %@", obj);
}
NSLog(@"%@", personArray);
告诉我我的数组中有哪些对象。但是我希望更深入一些,我希望能够看到每个对象的属性。我只是不确定如何定位它们。
以下是我正在使用的代码: 人是我的自定义对象。
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);
答案 0 :(得分:14)
您必须在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);
之间没有太大的区别,但它更有用,因为一旦你创建了描述方法就不必重写它,你只需要打印对象。
答案 1 :(得分:6)
除了在所有类中使用描述方法之外,还有一种简单的方法。
使用ICHObjectPrinter:
NSLog(@"Object description is %@",[ICHObjectPrinter descriptionForObject:person]);
答案 2 :(得分:2)
要打印一个对象的所有属性,请使用以下代码:
- (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(@"-----------------------------------------------");
}
答案 3 :(得分:1)
要获得更高级的解决方案,请查看此答案https://stackoverflow.com/a/2304797/519280。您可以将此代码添加到Person对象扩展的基类中,从那时起,您可以使用autoDescribe函数自动打印对象的所有属性,而无需经过手动列出所有属性的过程。描述方法。