Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static method (which isn't class method) in objective C

While reading THIS question and accepted answer for the question, I was unable to get the difference between these two types of methods. Actually got the point by reading the example, but then, I was not able to write my own static method.

I tried googling create static method in objective c static methods

Which returned me links to THIS and THIS question. But, the example here are CLASS methods as per the first link in the question. Which is confusing me.

Can anyone here show me how do I create a static method which is not a class method ?

Any light on this would be appreciated.

like image 863
viral Avatar asked Apr 12 '13 07:04

viral


People also ask

Can we define static method outside the class?

could I also use it as a.f outside the class? Yes. You can use the static method if it is declared as public : public static void f() { // ... }

Do static methods belong to the class?

A static method belongs to the class rather than object of a class. A static method can be invoked without the need for creating an instance of a class.

Can static method be called by object?

Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.

Can we use static method in non-static method?

A static method can only access static data members and static methods of another class or same class but cannot access non-static methods and variables.


1 Answers

The problem you are having is the following - there are no static methods in Obj-C, that's why you cannot create them.

The difference between static and class methods is a difference between language concepts. You can find static methods in languages like Java or C++, you will find class methods in languages like Obj-C and Ruby.

The principal difference is that

  1. Static methods are shared between all instances (this doesn't exist in Obj-C). They are dispatched statically (at compile time) depending on the type of the variable.

  2. Class method is a method on a class. In languages like Obj-C and Ruby a class itself is an instance of another class (metaclass). Using + before a method declaration means the method will be defined on the class. Technically, it's just an instance method, just on a different object.

Don't worry if you don't understand the concept of class method perfectly, it takes time. To simplify, you can consider it as a method shared between instances, but it can be overriden in subclasses.

like image 103
Sulthan Avatar answered Sep 27 '22 16:09

Sulthan