Obj-C using @selector on a static method from a static method in the same class?

I have two static methods / selectors in one class, one the other, as an external method callback. However, as I encoded it, I get an error message. This worked when both methods were instance methods, and I read that it can work when the first method is an instance method using [self class]. However, I did not find the information when it is static, and I did not get it to work.

+(void)Validate { Callback *managerCallback = [[[Callback alloc] initWithTarget:self Action:@selector(Parse:)] autorelease]; ... } +(void)Parse:(Callback *)managerCallback { ... } 

Thanks!

+4
source share
2 answers

Callback * managerCallback = [[[[Callback alloc] initWithTarget: self Action: @selector (Parse :)] autorelease];

This line of code is configured to invoke the Parse: instance method, and not the class method as you defined it.

Objective-C has no static methods. It has class methods and instance methods.

In addition, your methods should begin with lowercase letters.

Herp da Derp. Dave is right.

Considering this:

 +(void)Validate { Callback *managerCallback = [[[Callback alloc] initWithTarget:self Action:@selector(Parse:)] autorelease]; ... } +(void)Parse:(Callback *)managerCallback { ... } 

Some comments:

  • methods must begin with lowercase letters

  • it is extremely difficult to use a class in such a role; even if you really only need one of them, use an instance. At the very least, an instance is a convenient bucket for abandoning fortune, and this will make refactoring much easier in the future if you ever need two.

  • The above template makes an assumption (and I'm sure) that the Callback instance is saved. For callbacks, timers, and some other patterns, this is typical; keep the target until the target is called up for the last time. Then release (or the author). However, notification centers do not. Delegates are generally not saved.

+4
source

It turns out that the code is written correctly to do what I wanted, but since callback was set to autorelease, the object was freed before the callback was processed.

+1
source

Source: https://habr.com/ru/post/1340501/


All Articles