Getting name of the class from an instance

后端 未结 7 2101
不思量自难忘°
不思量自难忘° 2021-01-30 07:45

I have the following problem: I get an instance of a class passed and want to know the name of the class of this instance. How to get this?

相关标签:
7条回答
  • 2021-01-30 08:17

    Just add a category:

    NSObject+Extensions.h
    - (NSString *)className;
    
    NSObject+Extensions.m
    - (NSString *)className {
        return NSStringFromClass(self.class);
    }
    

    Then use the following code:

    NSString *className = [[SomeObject new] className];
    

    or even:

    NSString *className = SomeObject.new.className;
    

    To use it anywhere add the category to YourProject.pch file.

    0 讨论(0)
  • 2021-01-30 08:17

    If you are looking how get classname in Swift you can use reflect to get information about object.

    let tokens = split(reflect(self).summary, { $0 == "." })
    if let typeName = tokens.last {
        println(typeName)
    }
    
    0 讨论(0)
  • 2021-01-30 08:19

    if all you want to do is test an object to see if it's a type of a certain Class

    BOOL test = [self isKindOfClass:[SomeClass class]];
    
    0 讨论(0)
  • 2021-01-30 08:28

    From within the class itself

    -(NSString *) className
    {
        return NSStringFromClass([self class]);
    }
    
    0 讨论(0)
  • 2021-01-30 08:29

    NSStringFromClass([instance class]) should do the trick.

    0 讨论(0)
  • 2021-01-30 08:36

    You can also use [[self class] description]

    0 讨论(0)
提交回复
热议问题