Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling non static method from static method on Objective C

How can I call a non-static method from a static method in same object?

Inside the static method: if I use [ClassName nonStaticMethod] Or If I use [self nonStaticMethod] I get warning: Class method '+isTrancparentImageWithUrl:' not found (return type defaults to 'id')

like image 891
Gal Avatar asked Dec 20 '22 21:12

Gal


2 Answers

One solution (and highly controversial) solution is to convert you class into a singleton implementation and then convert all static methods into regular methods.

EG if you had a class called FileManager and in there you had a method which looked like

+ (NSString *) getDocumentsDirectory

and for whatever reason you wanted to call a nonstatic method from inside there you would need to change your implementation to be something like this

+ (FileManager *)sharedInstance {
    // Singleton implementation
    static FileManager* instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[FileManager alloc] init];
    });
    return instance;
}

- (NSString *) getDocumentsDirectory

And instead of calling

[FileManager getDocumentsDirectory]; 

you would call

[[FileManager sharedInstance] getDocumentsDirectory];

There are several reasons as to why you wouldn't want to create a singleton, however, that is beyond the scope of my response :).

like image 169
endy Avatar answered Jan 27 '23 02:01

endy


You need to create the object of the class to call non class methods, You need an instance to call such methods that is why those methods are called instance methods.

calling [self instanceMethod] from class method wont work, because self in class method points to the class rather any instance. Here you can find information the on use of self in class methods.

like image 27
Vignesh Avatar answered Jan 27 '23 03:01

Vignesh