Getting name of the class from an instance

后端 未结 7 2188
不思量自难忘°
不思量自难忘° 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.

提交回复
热议问题