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
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
And instead of calling
you would call
There are several reasons as to why you wouldn't want to create a singleton, however, that is beyond the scope of my response :).
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 forClassName
. It is defined forClassName
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 noself
-because there's no object(instance). You may workaround it, using singleton pattern i posted above.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.
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, becauseself
in class method points to the class rather any instance. Here you can find information the on use ofself
in class methods.