Search code examples
core-datansmanagedobjectnsset

How do I check if an NSSet contains an object of a kind of class?


How would you implement the following instance method for NSSet:

- (BOOL)containsMemberOfClass:(Class)aClass

Here's why I want to know:

Core Data model: enter image description here

How do I add a Facebook authorization to a user's authorizations NSSet, but only if one doesn't already exist. In other words, a user can have many authorizations (in case I choose to add a Twitter (e.g.) authorization in the future) but should only have one of each kind of authorization. So, if (![myUser.authorizations containsMemberOfClass:[Facebook class]]), then add a Facebook authorization instance to myUser.


Solution

  • Unfortunately, you have to loop through all of the authorizations and check:

    @interface NSSet (ContainsAdditions)
    
    - (BOOL)containsKindOfClass:(Class)class;
    - (BOOL)containsMemberOfClass:(Class)class;
    
    @end
    
    @implementation NSSet (ContainsAdditions)
    
    - (BOOL)containsKindOfClass:(Class)class {
        for (id element in self) {
            if ([element isKindOfClass:class])
                return YES;
        }
        return NO;
    }
    
    - (BOOL)containsMemberOfClass:(Class)class {
        for (id element in self) {
            if ([element isMemberOfClass:class])
                return YES;
        }
        return NO;
    }
    
    @end