如何打印(NSLog)添加到NSMutableArray的自定义对象的属性 [英] How to Print out(NSLog) the properties of a custom object added to a NSMutableArray

查看:357
本文介绍了如何打印(NSLog)添加到NSMutableArray的自定义对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a custom object that I create with 3 properties defined in it. I create the object and assign the values to those properties. After that I put that object into an NSMutable Array. I know I can use :

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

告诉我数组中有哪些对象。但我想更深入一点,我希望能够看到每个对象的属性。我只是不确定如何定位它们。

To tell me what kind of objects are in my array. But I want to go a level deeper, I want to be able to see what the properties are for each of those objects. I'm just not sure how to target them.

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

Here is the code and I am using: Person is my custom object.

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);


推荐答案

你必须使用描述 Person类中的方法

You have to use the description method inside your Person class

-(NSString *)description{

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

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

This way you can print always the object you have inside your NSArray but instead of the memory description you'll get returned the values you've defined before in your description method of the specific object.

如果您只想使用 NSArray 中的元素使用占位符:

If you just want to do this with the element from the NSArray use placeholders:

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

之间没有太大区别,但它更有用,因为你不必重写一次你已经创建了描述方法,你只需要打印对象。

There is not much difference between, but its more useful because you don't have to rewrite it once you have created your description method, you just have to print the object.

这篇关于如何打印(NSLog)添加到NSMutableArray的自定义对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆