0

is there any advantage when use class method instead of instance method? For Objective-c :

class method:
use symbol + (void) method;
call: [Class method];


instance method:
use symbol - (void) method;
call: [class.obj method];
seguedestination
  • 419
  • 4
  • 19

2 Answers2

0

My explanation is a little different.

Instance methods are sent to an INSTANCE of a class. An instance of a class is a concrete thing. It has state data that persists for the life of the object. When you send a message to an object, it can use that state data to do things, and it can remember information for later.

Class methods are sent to the class as a whole. A class is a more abstract concept. Classes do not save state data, at least in Objective C (In other languages like C++, there are class variables that belong to the entire class, but Objective C does not have class variables.)

Lets move to an example of a car factory

The car factory is the class. The car class has a class method buildCar. The buildCar method takes parameters that tell what color the car should be, how big the engine should be, what options it should have, etc. You sent the car factory (the class) a buildCar message, and it creates and returns an instance of that class (the car factory builds you a car and gives it to you.)

Once you've created a car, that particular car has state variables that store things like the channel on the radio, the amount of gas left in the tank, the milage ("kilometerage"?) on the odometer, the wear level on the brakes, etc. Different cars will have different values for those variables.

You can ask an individual car how much gas is left in it's tank. (instance method.) Car A might have a full tank, and car B might be nearly empty.

However, it would not make sense to ask the car factory how much gas it has in the tank. A car factory doesn't have a gas tank. However, you could ask a car factory about the types of cars that it can build and the options for those cars. That is static information that always holds true for that car factory.

In addition to "factory methods" (e.g. build me a car), you can use class methods like you use functions in a procedural language. A class method is self-contained. You pass all the parameters into the method that you need in order to do whatever task is required, and you get back a single result (or no result for a void class method.) Once the class method is done executing, there is no state data left to record what happened.

DHEERAJ
  • 1,478
  • 12
  • 32
-2

This is not a matter of advantage. It's like asking if there is any advantage using a hammer instead of a saw. The question is nonsense; you use a hammer for hammering and a saw for sawing.

You use instance methods for things relating an instance of the class. You use class methods for things relating to the class as a whole.

gnasher729
  • 51,477
  • 5
  • 75
  • 98