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')
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.
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 can't
You can call static method/variables in instance methods, but not the other way.
Reason is simple, the static methods are binded to the class, not the instances (objects) of the class.
You can create an instance of the current class and then call it on that, but it's not recommended to do that. Static methods can't call non-static ones - there is no 'this' in a static context.
There is no static
method in Objective-C. If you want to call [Class method]
it is called class methods(not static in terms of ANSI C)
However, you may find Singleton
pattern useful : http://cocoadev.com/wiki/SingletonDesignPattern
(basically, you hold static shared instance of an object)
edit:
[ClassName instanceMethod]
- nonStaticMethod
is not defined for ClassName
. It is defined for ClassName
objects(instances), so you cannot use it(it doesn't exist), app may crash.
[self instanceMethod]
- you cannot use that either, because when calling class method, there is no self
-because there's no object(instance). You may workaround it, using singleton pattern i posted above.