1

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');"];
}
David Marcus
  • 454
  • 3
  • 20

1 Answers1

1

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.

bbum
  • 162,346
  • 23
  • 271
  • 359
  • 1
    Thanks for that analogy. I understand the problem now, and I also get your proposed solution of making a global variable to represent the class. I'm just starting Objective-C, so I'm going to try to figure out how to do that. – David Marcus May 19 '17 at 19:59
  • @DavidMarcus The concept of "class" vs. "instance" trips everyone up when they are starting in any OO language. The other one that you'll run into is automatic instantiation. I.e. if you have a XIB file, the act of loading the XIB causes a bunch of instances to be created. Thus, creating a *new* instance isn't really appropriate. You have to use the mechanisms provided by the system to get at the instances that fell out of loading. – bbum May 19 '17 at 20:03
  • Thanks for the heads up on that. – David Marcus May 19 '17 at 20:08
  • so basically `self` in a class method is like referring to a static method? – Daniel Lizik Feb 21 '19 at 05:19
  • @DanielLizik Pretty much. The key difference being that Objective-C class methods can be overridden and/or swizzled, which is not the case with true static methods. https://stackoverflow.com/questions/8089186/whats-the-difference-between-class-method-and-static-method – bbum Feb 22 '19 at 00:11