How would you implement the following instance method for NSSet
:
- (BOOL)containsMemberOfClass:(Class)aClass
Here's why I want to know:
Core Data model:
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
.
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