How to detect a property return type in Objective-C

后端 未结 6 1752
南旧
南旧 2020-12-05 11:10

I have an object in objective-c at runtime, from which I only know the KVC key and I need to detect the return value type (e.g. I need to know if its an NSArray or NSMutable

6条回答
  •  醉话见心
    2020-12-05 11:31

    The preferred way is to use the methods defined in the NSObject Protocol.

    Specifically, to determine if something is either an instance of a class or of a subclass of that class, you use -isKindOfClass:. To determine if something is an instance of a particular class, and only that class (ie: not a subclass), use -isMemberOfClass:

    So, for your case, you'd want to do something like this:

    // Using -isKindOfClass since NSMutableArray subclasses should probably
    // be handled by the NSMutableArray code, not the NSArray code
    if ([anObject isKindOfClass:NSMutableArray.class]) {
        // Stuff for NSMutableArray here
    } else if ([anObject isKindOfClass:NSArray.class]) {
        // Stuff for NSArray here
    
        // If you know for certain that anObject can only be
        // an NSArray or NSMutableArray, you could of course
        // just make this an else statement.
    }
    

提交回复
热议问题