开发者

In Objective-C, when should I use class methods and when should I use instance methods?

开发者 https://www.devze.com 2023-01-05 00:39 出处:网络
Wha开发者_StackOverflow社区t is the difference between class and instance methods in Objective-C and when should I use each of them?Using the tired old Car analogy...

Wha开发者_StackOverflow社区t is the difference between class and instance methods in Objective-C and when should I use each of them?


Using the tired old Car analogy...

Think of a Class like it is a factory that makes Instances of the class. For example, you might have a Car class and you might declare a method like:

+ carWithColor: (NSColor *) aColor;

And that method would then create a new Car instance, set the color, and return it:

 + carWithColor: (NSColor *) aColor
 {
     Car *aCar = [[[self alloc] init] autorelease];
     [aCar paintWithColor: aColor];
     return aCar;
 }

Now, that Car class would then declare an instance method that allows the car to be painted. Why an instance method? Because every car can have a different color (and the color of the car would likely be stored in an instance variable).

- (void) paintWithColor: (NSColor *) aColor
{
    ... do your paint stuff here ...
}

This is explained in the Objects, Classes, and Messaging section of the Objective-C documentation.


This is an old post, but since it comes up first in a Google search I thought I'd add to it.

I'm not going to talk about class methods used as factory methods. I'd like to talk about their use in utility methods. You can/should use class methods for utility methods that are independent of state. What does this mean? Well, for instance, if you're formatting a date the same way for all instances, that's a utility method that should be a class method. Think of the utility method like a screw driver. You don't need to make a new instance of the screw driver every time you want to do something with it. The screw driver remains constant. So, for instance, I have a class that includes a private method that generates a string of emDashes used for displaying to the view. This method is not dependent on state and hence will not vary by instance. Think of class utility methods like constants.

+ (NSString *)emDashString {
return @"   \u2014 \u2014 \u2014 \u2014 \u2014 \u2014 \u2014 \u2014 \u2014";

}

You can call this method generically within the class (it's private in my example) like this:

NSString *string = [[self class] emDashString ];

I've deliberately chosen a bit of a trivial example to drive the point home. You would only bother making this a class utility method if you're going to need this string more than once in your class. Notice that instead of referring to the class by name I call it generically with [self class] since this is called internally. If it's exposed and you want to call it from another class then refer to it by the class name as usual.


Instance methods do things with instances of a class:

NSString *myString;
myString = [[[NSString alloc] initWithString:@"Hello, world."] autorelease];
NSLog (@"myString's length: %u", [myString length]); // instance method

Class methods can do class-specific things without relying on an object instance, often returning an instance of the class, or some other class-specific result:

NSLog (@"%@", [NSString stringWithString:@"Hello, world."]); // class method

I think it may be rare to see class methods that do not return something.


You don't need to implement both. Either option is available to you as you design your class.

An instance method can operate on an instance of the class. This can get or set a property, or cause behavior you only want that instance to perform. You need to actually have an instance to use it. These can either use or change the state of the instance.

// Notional instance methods
myHouse.color = blueColor;

[myCar accelerate];
speed = myCar.speed;

A class method operates on the notion that the class exists. It can be used to create an instance, or perform a calculation that doesn't depend on having an instance. You might have a class for custom math helper, that essentially contains functions.

// Notional class method uses
myString = [NSString stringWithFormat:@"&f", floatToConvert];

myResult = [MyMathHelper MyFunctionWithInput:myInput];


Class method signatures are prefixed with +, instance methods with - so in your header file declarations would look something like this:

-(void)setAllThings:(NSArray*)things; //instance method
+(void)setAllClassThings:(NSArray*)things; //class method

And of course the same rules apply when you define the methods in the .m file.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号