objective-c 类方法和实例方法有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1053592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between class and instance methods?
提问by Devoted
What's the difference between a class method and an instance method?
类方法和实例方法有什么区别?
Are instance methods the accessors (getters and setters) while class methods are pretty much everything else?
实例方法是访问器(getter 和 setter),而类方法几乎是其他所有东西吗?
回答by Cory Kilger
Like most of the other answers have said, instance methods use an instance of a class, whereas a class method can be used with just the class name. In Objective-C they are defined thusly:
就像大多数其他答案所说的那样,实例方法使用类的实例,而类方法可以仅使用类名。在 Objective-C 中,它们是这样定义的:
@interface MyClass : NSObject
+ (void)aClassMethod;
- (void)anInstanceMethod;
@end
They could then be used like so:
然后可以像这样使用它们:
[MyClass aClassMethod];
MyClass *object = [[MyClass alloc] init];
[object anInstanceMethod];
Some real world examples of class methods are the convenience methods on many Foundation classes like NSString's +stringWithFormat:or NSArray's +arrayWithArray:. An instance method would be NSArray's -countmethod.
类方法的一些真实示例是许多 Foundation 类(如NSString's+stringWithFormat:或NSArray's )上的便捷方法+arrayWithArray:。实例方法将是NSArray的-count方法。
回答by Johannes Fahrenkrug
All the technical details have been nicely covered in the other answers. I just want to share a simple analogy that I think nicely illustrates the difference between a class and an instance:
所有技术细节都在其他答案中得到了很好的介绍。我只想分享一个简单的类比,我认为它很好地说明了类和实例之间的区别:


A classis like the blueprintof a house: You only have one blueprint and (usually) you can't do that much with the blueprint alone.
一个类就像房子的蓝图:你只有一个蓝图,(通常)你不能单独用蓝图做那么多。


An instance(or an object) is the actual housethat you build based on the blueprint: You can build lots of houses from the same blueprint. You can then paint the walls a different color in each of the houses, just as you can independently change the properties of each instance of a class without affecting the other instances.
一个实例(或对象)是实际的房子,你构建基于蓝图:您可以从同一个蓝图建造大量房屋。然后,您可以为每个房屋的墙壁涂上不同的颜色,就像您可以独立更改类的每个实例的属性而不影响其他实例一样。
回答by micmoo
Like the other answers have said, instance methods operate on an object and has access to its instance variables, while a class method operates on a class as a whole and has no access to a particular instance's variables (unless you pass the instance in as a parameter).
就像其他答案所说的那样,实例方法对对象进行操作并可以访问其实例变量,而类方法对整个类进行操作并且无法访问特定实例的变量(除非您将实例作为范围)。
A good example of an class method is a counter-type method, which returns the total number of instances of a class. Class methods start with a +, while instance ones start with an -.
For example:
类方法的一个很好的例子是计数器类型方法,它返回类的实例总数。类方法以 a 开头+,而实例方法以 a开头-。例如:
static int numberOfPeople = 0;
@interface MNPerson : NSObject {
int age; //instance variable
}
+ (int)population; //class method. Returns how many people have been made.
- (id)init; //instance. Constructs object, increments numberOfPeople by one.
- (int)age; //instance. returns the person age
@end
@implementation MNPerson
- (id)init{
if (self = [super init]){
numberOfPeople++;
age = 0;
}
return self;
}
+ (int)population{
return numberOfPeople;
}
- (int)age{
return age;
}
@end
main.m:
主.m:
MNPerson *micmoo = [[MNPerson alloc] init];
MNPerson *jon = [[MNPerson alloc] init];
NSLog(@"Age: %d",[micmoo age]);
NSLog(@"%Number Of people: %d",[MNPerson population]);
Output: Age: 0 Number Of people: 2
输出:年龄:0 人数:2
Another example is if you have a method that you want the user to be able to call, sometimes its good to make that a class method. For example, if you have a class called MathFunctions, you can do this:
另一个例子是,如果您有一个希望用户能够调用的方法,有时将其设为类方法会很好。例如,如果您有一个名为 MathFunctions 的类,您可以这样做:
+ (int)square:(int)num{
return num * num;
}
So then the user would call:
那么用户会调用:
[MathFunctions square:34];
without ever having to instantiate the class!
无需实例化类!
You can also use class functions for returning autoreleased objects, like NSArray's
你也可以使用类函数来返回自动释放的对象,比如 NSArray 的
+ (NSArray *)arrayWithObject:(id)object
That takes an object, puts it in an array, and returns an autoreleased version of the array that doesn't have to be memory managed, great for temperorary arrays and what not.
这需要一个对象,把它放在一个数组中,然后返回一个不需要内存管理的数组的自动发布版本,非常适合临时数组等等。
I hope you now understand when and/or why you should use class methods!!
我希望你现在明白什么时候和/或为什么应该使用类方法!!
回答by Robert Horvick
An instance method applies to an instance of the class (i.e. an object) whereas a class method applies to the class itself.
实例方法适用于类的实例(即对象),而类方法适用于类本身。
In C# a class method is marked static. Methods and properties not marked static are instance methods.
在 C# 中,类方法被标记为静态。未标记为静态的方法和属性是实例方法。
class Foo {
public static void ClassMethod() { ... }
public void InstanceMethod() { ... }
}
回答by hhafez
The answer to your question is not specific to objective-c, however in different languages, Class methods may be called static methods.
您的问题的答案并非特定于 Objective-c,但是在不同的语言中,类方法可能被称为静态方法。
The difference between class methods and instance methods are
类方法和实例方法的区别是
Class methods
类方法
- Operate on Class variables (they can not access instance variables)
- Do not require an object to be instantiated to be applied
- Sometimes can be a code smell (some people who are new to OOP use as a crutch to do Structured Programming in an OO enviroment)
- 对类变量进行操作(它们不能访问实例变量)
- 不需要实例化对象才能应用
- 有时可能是代码异味(一些 OOP 新手用作在 OO 环境中进行结构化编程的拐杖)
Instance methods
实例方法
- Operate on instances variables and class variables
- Must have an instanciated object to operate on
- 对实例变量和类变量进行操作
- 必须有一个实例化的对象来操作
回答by Adam Waite
I think the best way to understand this is to look at allocand init. It was this explanation that allowed me to understand the differences.
我认为理解这一点的最好方法是查看alloc和init。正是这种解释让我了解了差异。
Class Method
类方法
A class method is applied to the class as a whole. If you check the allocmethod, that's a class method denoted by the +before the method declaration. It's a class method because it is applied to the class to make a specific instance of that class.
类方法作为一个整体应用于类。如果您检查该alloc方法,则该方法是由+方法声明之前的表示的类方法。它是一个类方法,因为它应用于类以创建该类的特定实例。
Instance Method
实例方法
You use an instance method to modify a specific instance of a class that is unique to that instance, rather than to the class as a whole. initfor example (denoted with a -before the method declaration), is an instance method because you are normally modifying the properties of that class after it has been created with alloc.
您可以使用实例方法来修改类的特定实例,该实例对该实例是唯一的,而不是整个类。init例如(-在方法声明之前用 a 表示)是一个实例方法,因为您通常在使用alloc.
Example
例子
NSString *myString = [NSString alloc];
You are calling the class method allocin order to generate an instance of that class. Notice how the receiver of the message is a class.
您正在调用类方法alloc以生成该类的实例。注意消息的接收者是一个类。
[myString initWithFormat:@"Hope this answer helps someone"];
You are modifying the instance of NSStringcalled myStringby setting some properties on that instance. Notice how the receiver of the message is an instance (object of class NSString).
您正在通过在该实例上设置一些属性来修改被NSString调用myString的实例。注意消息的接收者是一个实例(类的对象NSString)。
回答by Siddharth
So if I understand it correctly.
所以如果我理解正确的话。
A classmethod does not need you to allocate instance of that object to use / process it. A classmethod is self contained and can operate without any dependence of the state of any object of that class. A classmethod is expected to allocate memory for all its own work and deallocate when done, since no instance of that class will be able to free any memory allocated in previous calls to the class method.
一个class方法不需要你来分配对象使用的实例/处理它。甲class方法是自包含的并且可以在不那类的任何对象的状态中的任意依赖性操作。一个class方法应该为它自己的所有工作分配内存并在完成后释放,因为该类的任何实例都不能释放在先前调用该类方法时分配的任何内存。
A instancemethod is just the opposite. You cannot call it unless you allocate a instance of that class. Its like a normal class that has a constructor and can have a destructor (that cleans up all the allocated memory).
甲instance方法是正好相反。除非您分配该类的实例,否则您无法调用它。它就像一个普通的类,它有一个构造函数,也可以有一个析构函数(清理所有分配的内存)。
In most probability (unless you are writing a reusable library, you should not need a classvariable.
在大多数情况下(除非您正在编写可重用的库,否则您不需要class变量。
回答by iosrookie
Class methods are usually used to create instances of that class
类方法通常用于创建该类的实例
For example, [NSString stringWithFormat:@"SomeParameter"];returns an NSStringinstance with the parameter that is sent to it. Hence, because it is a Class method that returns an object of its type, it is also called a convenience method.
例如,[NSString stringWithFormat:@"SomeParameter"];返回一个NSString带有发送给它的参数的实例。因此,因为它是一个返回其类型对象的类方法,所以它也被称为便利方法。
回答by eduffy
Instances methods operate on instances of classes (ie, "objects"). Class methods are associated with classes (most languages use the keyword staticfor these guys).
实例方法对类的实例(即“对象”)进行操作。类方法与类相关联(大多数语言static对这些人使用关键字)。
回答by sicklebrick
Take for example a game where lots of cars are spawned.. each belongs to the class CCar. When a car is instantiated, it makes a call to
以生成大量汽车的游戏为例..每个都属于 CCar 类。当汽车被实例化时,它会调用
[CCar registerCar:self]
So the CCar class, can make a list of every CCar instantiated.
Let's say the user finishes a level, and wants to remove all cars... you could either:
1- Go through a list of every CCar you created manually, and do whicheverCar.remove();or
2- Add a removeAllCars method to CCar, which will do that for you when you call [CCar removeAllCars]. I.e. allCars[n].remove();
所以 CCar 类,可以让每个 CCar 实例化的列表。假设用户完成了一个关卡,并且想要移除所有汽车……您可以: 1- 浏览您手动创建的每个 CCar 的列表,然后执行whicheverCar.remove();或 2- 向 CCar 添加 removeAllCars 方法,这将执行此操作当您调用 [CCar removeAllCars] 时为您服务。IE allCars[n].remove();
Or for example, you allow the user to specify a default font size for the whole app, which is loaded and saved at startup. Without the class method, you might have to do something like
或者,例如,您允许用户为整个应用程序指定默认字体大小,该字体大小在启动时加载和保存。如果没有类方法,您可能必须执行类似的操作
fontSize = thisMenu.getParent().fontHandler.getDefaultFontSize();
With the class method, you could get away with [FontHandler getDefaultFontSize].
使用 class 方法,您可以摆脱[FontHandler getDefaultFontSize].
As for your removeVowels function, you'll find that languages like C# actually have both with certain methods such as toLower or toUpper.
至于您的 removeVowels 函数,您会发现像 C# 这样的语言实际上同时具有某些方法,例如 toLower 或 toUpper。
e.g. myString.removeVowels()and String.removeVowels(myString)(in ObjC that would be [String removeVowels:myString]).
例如myString.removeVowels()和 String.removeVowels(myString)(在 ObjC 中就是[String removeVowels:myString])。
In this case the instance likely calls the class method, so both are available. i.e.
在这种情况下,实例可能会调用类方法,因此两者都可用。IE
public function toLower():String{
return String.toLower();
}
public static function toLower( String inString):String{
//do stuff to string..
return newString;
}
basically, myString.toLower()calls [String toLower:ownValue]
基本上,myString.toLower()调用 [String toLower:ownValue]
There's no definitive answer, but if you feel like shoving a class method in would improve your code, give it a shot, and bear in mind that a class method will only let you use other class methods/variables.
没有明确的答案,但是如果您觉得将类方法推入可以改进您的代码,请试一试,并记住类方法只会让您使用其他类方法/变量。

