代码之家  ›  专栏  ›  技术社区  ›  futureelite7 Adam Rosenfield

如何测试Objective-C中的对象是哪个类?

  •  205
  • futureelite7 Adam Rosenfield  · 技术社区  · 15 年前

    如何测试对象是否是Objective-C中特定类的实例?假设我想看看对象a是类b的实例,还是类c的实例,我该怎么做呢?

    6 回复  |  直到 11 年前
        1
  •  347
  •   Muruganandham K    8 年前

    [yourObject isKindOfClass:[a class]]
    // Returns a Boolean value that indicates whether the receiver is an instance of 
    // given class or an instance of any class that inherits from that class.
    

    [yourObject isMemberOfClass:[a class]]
    // Returns a Boolean value that indicates whether the receiver is an instance of a 
    // given class.
    

    NSStringFromClass 功能:

    NSString *className = NSStringFromClass([yourObject class]);
    

    或objective-c运行时api中的c函数:

    #import <objc/runtime.h>
    
    /* ... */
    
    const char* className = class_getName([yourObject class]);
    NSLog(@"yourObject is a: %s", className);
    

    编辑: 迅速地

    if touch.view is UIPickerView {
        // touch.view is of type UIPickerView
    }
    
        2
  •  21
  •   Clement M    12 年前

    你也可以使用

    NSString *className = [[myObject class] description]; 
    

    在任何对象上

        3
  •  3
  •   Duke    11 年前

    这是一种阶级 在Apple文档中

    在类集群表示的对象上使用此方法时要小心。由于类集群的性质,您返回的对象可能并不总是您期望的类型。如果您调用一个返回类集群的方法,那么该方法返回的确切类型就是您可以对该对象执行的操作的最佳指示器。例如,如果方法返回指向NSArray对象的指针,则不应使用此方法查看数组是否可变,如以下代码所示:

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

    如果在代码中使用这样的构造,您可能会认为修改实际上不应该修改的对象是正确的。这样做可能会给其他希望对象保持不变的代码带来问题。

        4
  •  2
  •   Inder Kumar Rathore user4622654    11 年前

    如果要检查特定类,则可以使用

    if([MyClass class] == [myClassObj class]) {
    //your object is instance of MyClass
    }
    
        5
  •  1
  •   Kuldeep Tanwar    9 年前

    如果要获取类的名称,只需调用:-

    id yourObject= [AnotherClass returningObject];
    
    NSString *className=[yourObject className];
    
    NSLog(@"Class name is : %@",className);
    
        6
  •  0
  •   Saranjith    8 年前

    您还可以检查运行时。在代码和内部(lldb)控制台写入中放置一个断点

    (lldb) po [yourObject class]
    

    这样地。。

    enter image description here

    推荐文章