Asserting an Object Class in Objective-C

I often claim that the object "isKindOfClass" of some class in Objective-C. I do it like this:

NSAssert([obj isKindOfClass:[AClass class]], @"%@ should be kind of class %@", obj, [[AClass class] description]);

I am wondering what is the best way to make a short cut. I am thinking of a macro definition, something like:

#define NSClassAssert(obj, class)  NSAssert([obj isKindOfClass:class], @"%@ should be of class %@", obj, [class description])

I am worried that this may cause some unpleasant compilation errors or run-time problems, is there something fundamentally wrong in this regard, is there an easy way to do this?

+5
source share
2 answers

You need to ask why you want to do this in the first place. You said:

, c, " ". , , , , .

, , , .. - :

- (void)doSomething:(NSArray *)array { /* Do something * }

- (void)doSomethingElse
{
    NSString *string = @"my string";
    [self doSomething:string];
}

, , .

, , id, , , assert:

- (id)doSomething:(id)obj
{
    if ([obj respondsToSelector:@selector(calculateSomething)]) {
        return [obj calculateSomething];
    } else {
        NSLog(@"%@ does not respond to calculateSomething", obj);
    }
}

.


, , , .

+3

, , , , .

, , , , ; , NSWhatEvers. Objective-C , ; ,

#define NSIsKindOf(obj, klass)  NSAssert([obj isKindOfClass:class], @"%@ should be of class %s but is a %@", obj, #klass, [obj class])

, .. , respondsToSelector:, @mipadi, - .

-1

All Articles