Haagenti
Haagenti

Reputation: 8144

Is method a class method or instance method

In my code I want to know if a method is a class method or an instance method. The code I am currently using works, but I wonder if there is a beter way.

Current code to "detect" if it is a class method or instance:

Method method = class_getInstanceMethod(class, selector);
if (method) {
  __strong Class object = [[class alloc] init];
  objc_msgSend(object, selector);
}else {
  method = class_getClassMethod(class, selector);
  if (method) {
    objc_msgSend(class, selector);
  }
}

Upvotes: 2

Views: 152

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

There's very little that you can improve beyond two if statements. You can use respondsToSelector: method instead, but since you do not have an object to start with, you will end up with an if inside an if rather than an a better-looking else if:

if ([class respondsToSelector:selector]) {
    // Call class method
} else {
    id object = [[class alloc] init];
    if ([object respondsToSelector:selector]) {
        // Call instance method
    }
}

If you could modify your program flow to start with an object instead of a class, you coud do this instead:

if ([object respondsToSelector:selector]) {
    // Call instance method
} else if ([[object class] respondsToSelector:selector]) {
    // Call class method
}

Upvotes: 3

Related Questions