Reputation: 12444
I have a NSArray that is filled with different types of objects. Lets say one is a NSDictionary and another is NSData. How would I randomly chose a object from this array and then check what kind of object it is. So if it a NSDictionary, I will do method A. Or if it is NSData, I will do method B.
How would I put this into code?
Thanks!
Upvotes: 2
Views: 2653
Reputation: 11425
Translated to Objective-C
id obj = [array methodThatReturnsARandomObject];
if ([obj isKindOfClass:[NSDictionary class]]) {
a();
} else if ([obj isKindOfClass:[NSData class]]) {
UIImage *image = [UIImage imageWithData:obj]
}
Or you can do
NSObject *obj = [array methodThatReturnsARandomObject];
if ([obj isKindOfClass:[NSDictionary class]]) {
a();
} else if ([obj isKindOfClass:[NSData class]]) {
UIImage *image = [UIImage imageWithData:(NSData *)obj]
}
Does not really matter.
Upvotes: 7
Reputation: 3634
You can use a random number generator that will get a number that is between 0 and the last index of your array. Then once you get the object you can use the isKindOfClass or isMemberOfClass method on the object that is returned from the array.
Upvotes: 1