Skip to content

Instantly share code, notes, and snippets.

@objectiveSee
Last active December 23, 2015 23:39
Show Gist options
  • Save objectiveSee/6711422 to your computer and use it in GitHub Desktop.
Save objectiveSee/6711422 to your computer and use it in GitHub Desktop.
Category that enforces objects in a dictionary are of the type I expect them to be.
/**
THE PROBLEM:
NSDictionary *d = [sever getMeta];
// d.score returns something of type 'NSArray'
NSNumber *userId = [d objectForKey:@"score"];
NSInteger i = [userId integerValue]; // <<------- Now what happens!
SOLUTION:
NSDictionary *d = [sever getMeta];
//Raises exception in DEBUG builds immediately if the Class is not a match
NSNumber *userId = [d objectForKey:@"score" ofClass:@"NSNumber"];
*/
@interface NSObject (AssertionCategories)
- (id)objectForKey:(id)aKey ofClass:(NSString *)aClassName;
- (id)objectForKey:(id)aKey ofClass:(NSString *)aClassName mustExist:(BOOL)mustExist;
@end
@implementation NSObject (AssertionCategories)
- (id)objectForKey:(id)aKey ofClass:(NSString *)aClassName;
{
return [self objectForKey:aKey ofClass:aClassName mustExist:YES];
}
- (id)objectForKey:(id)aKey ofClass:(NSString *)aClassName mustExist:(BOOL)mustExist {
id object = [(NSDictionary *)self objectForKey:aKey];
#ifdef DEBUG
// if object exists, check the class
// if it doesn't, check whether mustExist is YES
// if it isn't, return the object (nil)
if (object) {
// cannot include this string directly in NSCAssert; but very helpful for debugging
NSString *errorString = [NSString stringWithFormat:@"Invalid kind of class; expected: %@, actual: %@",
aClassName,
NSStringFromClass([object class])];
NSCAssert([object isKindOfClass:NSClassFromString(aClassName)] == YES,errorString);
} else if (mustExist) {
NSString *errorString = @"Object does not exist!";
NSCAssert(NO,errorString);
}
#endif
return object;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment