FooType *myFoo = nil; for (id obj in myArray) { if ( [obj isKindOfClass:[FooType class]] ) myFoo = obj; }
有了Objective-C和NSArray的所有好东西,就必须有更好的方法,对吧?
FooType *myFoo = nil; NSUInteger index = [myArray indexOfObjectPassingTest:^BOOL (id obj,NSUInteger idx,BOOL *stop) { return [obj isKindOfClass:[FooType class]]; }]; if (index != NSNotFound) myFoo = [myArray objectAtIndex:index];
它不是真的更短.您可以考虑编写自己的NSArray方法来执行此操作.