Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

ios - How to Print out(NSLog) the properties of a custom object added to a NSMutableArray

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.

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to use the description method inside your Person class

-(NSString *)description{

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...