365Cocoa

A snippet of Objective-C code per day, 365 days long.
Written by Pieter Omvlee, developer and owner of Bohemian Coding.

Mar 27

Day 29: -containsObjectOfClass:

Today I’ll be going back to the very beginning of 365Cocoa with a category on NSArray. I do find that I often need to see if an array contains objects of a certain class. One use is in validating menu and toolbar items for example; based on the layers you might have selected you want to enable/disable some items. This method takes perfect care of that:

- (BOOL)containsObjectOfClass:(Class)aClass
{
  for (id obj in self) {
    if ([obj isKindOfClass:aClass])
      return YES;
  }
  return NO;
}