Search code examples
objective-ccordovaphonegap

How To Use self On A Class Method In Objective C


I'm trying to make a custom Cordova plugin, and I'd like to make a method in Objective-C that calls the javascript function alert('text');

This is how I normally do it, and it works well.

- (void)myMethod:(CDVInvokedUrlCommand*)command
{
    [self.commandDelegate evalJs:@"alert('text');"];
}

The problem is that I need to do the same thing using a class method. If I change the - to +, I get an error message.

+ (void)myMethod:(CDVInvokedUrlCommand*)command
{
    [self.commandDelegate evalJs:@"alert('text');"];
}

Solution

  • Think of this way; an instance is a like a car and the class is like the factory that built the car.

    Every car has a different driver (delegate), but the factory does not have access to each car's driver unless they specifically engineered a way to gain access (like, say, through On-Star).


    So, therein is your problem. You are trying to access instance state from outside the scope of the instance. In a class method, self refers to the Class, not to any specific instance.

    The solution can be one of several. You could use a singleton; a single instance of that class that is used globally in your program, for example.