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')
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 :).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With