Strict Type Checking in Objective-C Part 2

前端 未结 2 1598
遥遥无期
遥遥无期 2020-12-19 21:09

In this question I was looking for a way to ensure that a variable is of a certain type using a define. But sometimes I have this situation:

- (void) theSitu         


        
相关标签:
2条回答
  • 2020-12-19 21:41

    When you get the arguments of a method (using method_copyArgumentType as mentioned in the other answer), the "type" it returns is either a C type (like int, float, etc) or just Object (returned as a "@"). Sadly it's not possible to get the objective-C type that a method is expecting — that information is lost when you compile.

    Answer to a similar problem found here.

    0 讨论(0)
  • 2020-12-19 21:45

    Hmm... Interesting question. I have a few things that should work (theoratically).

    You can get the function name that is being executed using __func__. (See this).

    You can get the Selector from a string:

    SEL selector = selectorFromString(@"doWork");
    

    You can get Method object of an instance of a class using objective C runtime.

    Method *m = class_getInstanceMethod(self, selector);
    

    You can get number of arguments of a method from:

    method_getNumberOfArguments
    

    you can get argument type using

    method_copyArgumentType
    

    And from here you should be able to assert.

    I know, long shot - I have not tried to run the code. I'll update the answer if I get on a Mac soon.

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