Reputation: 3955
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?
Upvotes: 3
Views: 2831
Reputation: 218
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
Upvotes: 2
Reputation: 52237
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)];
Upvotes: 6