3

I have an array of custom objects, but I can't NSLog the property of an individual object in that array because you can store any objects in an array. How would I go about doing this?

2
  • Are all the objects in your array of the same type? If so, can't you cast the object and access whichever property you need? Commented Jan 15, 2012 at 5:43
  • 1
    Casting is not necessary in Objective-C, as it's Runtime offers a decent degree of introspection. Commented Jan 15, 2012 at 5:47

2 Answers 2

6

Objective-C offers several introspection techniques trough it runtime system.

You can ask a object, if it is from a certain kind, or responses to a certain message.

for (id anObject in array ){
    if([anObject isKindOfClass:[MyClass class]]){
        MyOtherClass *obj = anObject.myProperty ;
        NSLog(@"%@", obj);
    }
}

and

for (id anObject in array ){
    if( [anObject respondsToSelector:@selector(aMethod)] ) {
        NSLog(@"%@",[anObject aMethod]);
    }
}

As properties usually results in synthesized methods, the second way should also work for them.

Also to mention — although not in the scope of this question:

Classes can also be ask, if they fulfill a certain protocol. And as Objects can tell there class, this is also possible:

[[anObject class] conformsToProtocol:@protocol(MyProtocol)];
Sign up to request clarification or add additional context in comments.

Comments

2

The above answer is correct for accessing individual fields. Just as a side note, there are also some interesting tricks that you can do with key-value path coding and Collection Operators when you have a collection like an array. For example, if you have a large array of objects with a small number of values for one field:

 NSArray *allObjects;

you can create an array with all of the unique values of one of your fields with the statement:

 NSArray *values=[allObjects valueForKeyPath:@"@distinctUnionOfObjects.myObjectsInterestingProperty"];

or you can find the average value of a field with the statement:

 NSNumber *average=[allObjects valueForKeyPath:@"@avg.myObjectsInterestingProperty"];

All of the other key-value path Collection Operators you can use this way are listed in Apple's Key-Value Programming Guide

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.