How do I test which class an object is in Objective-C?

前端 未结 6 1195

How do I test whether an object is an instance of a particular class in Objective-C? Let\'s say I want to see if object a is an instance of class b, or class c, how do I go

6条回答
  •  天命终不由人
    2020-11-30 17:14

    What means about isKindOfClass in Apple Documentation

    Be careful when using this method on objects represented by a class cluster. Because of the nature of class clusters, the object you get back may not always be the type you expected. If you call a method that returns a class cluster, the exact type returned by the method is the best indicator of what you can do with that object. For example, if a method returns a pointer to an NSArray object, you should not use this method to see if the array is mutable, as shown in the following code:

    // DO NOT DO THIS!
    if ([myArray isKindOfClass:[NSMutableArray class]])
    {
        // Modify the object
    }
    

    If you use such constructs in your code, you might think it is alright to modify an object that in reality should not be modified. Doing so might then create problems for other code that expected the object to remain unchanged.

提交回复
热议问题