类和实例方法的区别是什么?

时间:2022-10-26 22:27:09

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),而类方法几乎是其他所有东西吗?

18 个解决方案

#1


648  

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 -count method.

类方法的一些现实示例是许多基础类上的方便方法,如NSString的+stringWithFormat:或NSArray的+arrayWithArray:。实例方法是NSArray的-count方法。

#2


185  

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 class is like the blueprint of 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 house that 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.

实例(或对象)是您根据蓝图构建的实际房屋:您可以从相同的蓝图中构建许多房屋。然后,您可以在每个房子中为墙壁涂上不同的颜色,就像您可以在不影响其他实例的情况下独立地更改类的每个实例的属性一样。

#3


101  

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:

类方法的一个很好的例子是反类型方法,它返回类的实例总数。类方法从一个+开始,而实例从一个-开始。例如:

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:

main.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!!

我希望您现在明白什么时候和/或为什么您应该使用类方法!!

#4


35  

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() { ... }
}

#5


15  

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
  • 必须有一个实例化对象来操作

#6


15  

I think the best way to understand this is to look at alloc and 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 alloc method, 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. init for 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(在方法声明之前用-表示)是一个实例方法,因为您通常是在使用alloc创建该类之后修改该类的属性。

Example

例子

NSString *myString = [NSString alloc];

You are calling the class method alloc in 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 NSString called myString by setting some properties on that instance. Notice how the receiver of the message is an instance (object of class NSString).

通过在该实例上设置一些属性,您正在修改名为myString的NSString实例。注意消息的接收者是一个实例(类NSString的对象)。

#7


6  

Class methods are usually used to create instances of that class

类方法通常用于创建该类的实例

For example, [NSString stringWithFormat:@"SomeParameter"]; returns an NSString instance 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实例。因此,因为它是返回类型对象的类方法,因此也称为方便方法。

#8


6  

So if I understand it correctly.

如果我理解正确的话。

A class method does not need you to allocate instance of that object to use / process it. A class method is self contained and can operate without any dependence of the state of any object of that class. A class method 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.

类方法不需要您分配该对象的实例来使用/处理它。类方法是自包含的,可以在不依赖于该类的任何对象的状态的情况下运行。类方法被期望为它自己的所有工作分配内存并在完成时释放内存,因为该类的任何实例都不能释放在以前调用类方法时分配的内存。

A instance method 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).

实例方法恰恰相反。除非分配该类的实例,否则不能调用它。它就像一个具有构造函数和析构函数(清除所有分配的内存)的普通类。

In most probability (unless you are writing a reusable library, you should not need a class variable.

在大多数情况下(除非您正在编写可重用库,否则不应该需要类变量。

#9


4  

Instances methods operate on instances of classes (ie, "objects"). Class methods are associated with classes (most languages use the keyword static for these guys).

实例方法对类的实例(即“对象”)进行操作。类方法与类相关联(大多数语言使用这些类的关键词静态)。

#10


3  

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的列表,并执行其中的evercar .remove();或者2-向CCar添加一个removeAllCars方法,当您调用[CCar removeAllCars]时,它将为您实现这一点。即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].

通过类方法,您可以避免使用[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]).

例如:mystrvowels()和strvowels (myString)(在ObjC中为[String removowels:myString])。

In this case the instance likely calls the class method, so both are available. i.e.

在这种情况下,实例可能调用类方法,因此这两个方法都是可用的。即。

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.

这里没有明确的答案,但是如果您想将类方法放入其中来改进您的代码,请尝试一下,并记住类方法只允许您使用其他类方法/变量。

#11


3  

class methods

类方法

are methods which are declared as static. The method can be called without creating an instance of the class. Class methods can only operate on class members and not on instance members as class methods are unaware of instance members. Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class.

是声明为静态的方法。可以在不创建类实例的情况下调用该方法。类方法只能操作类成员而不能操作实例成员,因为类方法不知道实例成员。类的实例方法也不能在类方法中调用,除非在该类的实例上调用它们。

Instance methods

实例方法

on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword. Instance methods operate on specific instances of classes. Instance methods are not declared as static.

另一方面,在调用类之前,需要一个类的实例存在,因此需要使用new关键字创建一个类的实例。实例方法对类的特定实例进行操作。实例方法没有声明为静态方法。

#12


3  

In Objective-C all methods start with either a "-" or "+" character. Example:

在Objective-C中,所有方法都以“-”或“+”字符开头。例子:

@interface MyClass : NSObject
// instance method
- (void) instanceMethod;

+ (void) classMethod;
@end

The "+" and "-" characters specify whether a method is a class method or an instance method respectively.

“+”和“-”字符分别指定方法是类方法还是实例方法。

The difference would be clear if we call these methods. Here the methods are declared in MyClass.

如果我们称这些方法为方法,区别就很明显了。这里的方法在MyClass中声明。

instance method require an instance of the class:

实例方法需要类的实例:

MyClass* myClass = [[MyClass alloc] init];
[myClass instanceMethod];

Inside MyClass other methods can call instance methods of MyClass using self:

在MyClass内部,其他方法可以使用self调用MyClass的实例方法:

-(void) someMethod
{
    [self instanceMethod];
}

But, class methods must be called on the class itself:

但是,类方法必须在类本身上调用:

[MyClass classMethod];

Or:

或者:

MyClass* myClass = [[MyClass alloc] init];
[myClass class] classMethod];

This won't work:

这不会工作:

// Error
[myClass classMethod];
// Error
[self classMethod];

#13


3  

CLASS METHODS


A class method typically either creates a new instance of the class or retrieves some global properties of the class. Class methods do not operate on an instance or have any access to instance variable.

类方法通常会创建类的新实例或检索类的一些全局属性。类方法不操作实例或对实例变量有任何访问权。


INSTANCE METHODS


An instance method operates on a particular instance of the class. For example, the accessors method that you implemented are all instance methods. You use them to set or get the instance variables of a particular object.

实例方法对类的特定实例进行操作。例如,您实现的访问器方法都是实例方法。您可以使用它们来设置或获取特定对象的实例变量。


INVOKE


To invoke an instance method, you send the message to an instance of the class.

要调用实例方法,请将消息发送到类的实例。

To invoke a class method, you send the message to the class directly.

要调用类方法,可以直接将消息发送给类。


Source: IOS - Objective-C - Class Methods And Instance Methods

源:IOS - Objective-C - Class方法和实例方法

#14


1  

Class methods can't change or know the value of any instance variable. That should be the criteria for knowing if an instance method can be a class method.

类方法不能改变或知道任何实例变量的值。这应该是判断实例方法是否可以是类方法的标准。

#15


1  

Also remember, the same idea applies to variables. You will come across terms like static, member, instance, class and so on when talking about variables the same as you would for methods/functions.

记住,同样的道理也适用于变量。在讨论变量时,您将遇到静态、成员、实例、类等术语,就像您在讨论方法/函数时遇到的那样。

It seems the common term in the Obj-C community is ivar for instance variable, but I am not an Obj-C guy, yet.

似乎object - c社区中常见的术语是ivar,例如变量,但我还不是object - c。

#16


1  

An update to the above answers, I agree instance methods use an instance of a class, whereas a class method can be used with just the class name.

对以上答案的更新,我同意实例方法使用类的实例,而类方法只能使用类名。

There is NO more any difference between instance method & class method after automatic reference counting came to existence in Objective-C.

在Objective-C中出现自动引用计数后,实例方法和类方法没有任何区别。

For Example[NS StringWithformat:..] a class method & [[NSString alloc] initwihtformat:..] an instance method, both are same after ARC

例如[NS StringWithformat:. .一个类方法& [[NSString alloc] initwihtformat:..]一个实例方法,在圆弧之后都是一样的

#17


1  

Note: This is only in pseudo code format

注意:这只是伪代码格式。

Class method

类方法

Almost does all it needs to do is during compile time. It doesn't need any user input, nor the computation of it is based on an instance. Everything about it is based on the class/blueprint——which is unique ie you don't have multiple blueprints for one class. Can you have different variations during compile time? No, therefore the class is unique and so no matter how many times you call a class method the pointer pointing to it would be the same.

它所需要做的几乎都是在编译期间。它不需要任何用户输入,也不需要基于实例进行计算。它的一切都基于类/蓝图——这是唯一的(一个类没有多个蓝图)。你能在编译期间有不同的变化吗?不,所以这个类是唯一的所以不管你调用了多少次类方法指针指向它的指针都是一样的。

PlanetOfLiving: return @"Earth" // No matter how many times you run this method...nothing changes.

Instance Method

实例方法

On the contrary instance method happens during runtime, since it is only then that you have created an instance of something which could vary upon every instantiation.

相反的实例方法在运行时发生,因为只有这样,您才创建了一个实例,该实例在每个实例化时都可能发生变化。

initWithName: @"John" lastName: @"Doe"Age:12 @"cool"
initWithName: @"Donald" lastName: @"Drumpf"Age:5 attitude:@"He started"
initWithName: @"President" lastName: @"Obama"Age:54 attitude: @"Awesome"
//As you can see the value can change for each instance.

If you are coming from other languages Static methods are same as class methods.
If you are coming from Swift, type methods are same as class methods.

如果您来自其他语言,静态方法与类方法相同。如果您来自Swift,类型方法与类方法相同。

#18


0  

Adding to above answers

增加以上的答案

Class method will work on class, we will use this for general purpose where like +stringWithFormat, size of class and most importantly for init etc

类方法将在类上使用,我们将使用它来实现一般用途,例如+stringWithFormat、类大小,最重要的是init等。

NSString *str = [NSString stringWithFormat:@"%.02f%%",someFloat];

NSString *str = [NSString stringWithFormat:@"%.02f% ",someFloat];

Instance Method will work on an instance of a class not on a class like we are having two persons and we want to get know the balance of each separately here we need to use instance method. Because it won't return general response. e.g. like determine the count of NSSArray etc.

实例方法将在一个类的实例上工作,而不是像我们这样有两个人的类,我们想要知道每个单独的平衡,我们需要使用实例方法。因为它不会返回一般的响应。例如确定NSSArray的计数等。

[johnson getAccountBalance];

[约翰逊getAccountBalance];

[ankit getAccountBalance];

[ankit getAccountBalance];

#1


648  

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 -count method.

类方法的一些现实示例是许多基础类上的方便方法,如NSString的+stringWithFormat:或NSArray的+arrayWithArray:。实例方法是NSArray的-count方法。

#2


185  

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 class is like the blueprint of 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 house that 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.

实例(或对象)是您根据蓝图构建的实际房屋:您可以从相同的蓝图中构建许多房屋。然后,您可以在每个房子中为墙壁涂上不同的颜色,就像您可以在不影响其他实例的情况下独立地更改类的每个实例的属性一样。

#3


101  

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:

类方法的一个很好的例子是反类型方法,它返回类的实例总数。类方法从一个+开始,而实例从一个-开始。例如:

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:

main.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!!

我希望您现在明白什么时候和/或为什么您应该使用类方法!!

#4


35  

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() { ... }
}

#5


15  

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
  • 必须有一个实例化对象来操作

#6


15  

I think the best way to understand this is to look at alloc and 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 alloc method, 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. init for 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(在方法声明之前用-表示)是一个实例方法,因为您通常是在使用alloc创建该类之后修改该类的属性。

Example

例子

NSString *myString = [NSString alloc];

You are calling the class method alloc in 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 NSString called myString by setting some properties on that instance. Notice how the receiver of the message is an instance (object of class NSString).

通过在该实例上设置一些属性,您正在修改名为myString的NSString实例。注意消息的接收者是一个实例(类NSString的对象)。

#7


6  

Class methods are usually used to create instances of that class

类方法通常用于创建该类的实例

For example, [NSString stringWithFormat:@"SomeParameter"]; returns an NSString instance 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实例。因此,因为它是返回类型对象的类方法,因此也称为方便方法。

#8


6  

So if I understand it correctly.

如果我理解正确的话。

A class method does not need you to allocate instance of that object to use / process it. A class method is self contained and can operate without any dependence of the state of any object of that class. A class method 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.

类方法不需要您分配该对象的实例来使用/处理它。类方法是自包含的,可以在不依赖于该类的任何对象的状态的情况下运行。类方法被期望为它自己的所有工作分配内存并在完成时释放内存,因为该类的任何实例都不能释放在以前调用类方法时分配的内存。

A instance method 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).

实例方法恰恰相反。除非分配该类的实例,否则不能调用它。它就像一个具有构造函数和析构函数(清除所有分配的内存)的普通类。

In most probability (unless you are writing a reusable library, you should not need a class variable.

在大多数情况下(除非您正在编写可重用库,否则不应该需要类变量。

#9


4  

Instances methods operate on instances of classes (ie, "objects"). Class methods are associated with classes (most languages use the keyword static for these guys).

实例方法对类的实例(即“对象”)进行操作。类方法与类相关联(大多数语言使用这些类的关键词静态)。

#10


3  

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的列表,并执行其中的evercar .remove();或者2-向CCar添加一个removeAllCars方法,当您调用[CCar removeAllCars]时,它将为您实现这一点。即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].

通过类方法,您可以避免使用[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]).

例如:mystrvowels()和strvowels (myString)(在ObjC中为[String removowels:myString])。

In this case the instance likely calls the class method, so both are available. i.e.

在这种情况下,实例可能调用类方法,因此这两个方法都是可用的。即。

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.

这里没有明确的答案,但是如果您想将类方法放入其中来改进您的代码,请尝试一下,并记住类方法只允许您使用其他类方法/变量。

#11


3  

class methods

类方法

are methods which are declared as static. The method can be called without creating an instance of the class. Class methods can only operate on class members and not on instance members as class methods are unaware of instance members. Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class.

是声明为静态的方法。可以在不创建类实例的情况下调用该方法。类方法只能操作类成员而不能操作实例成员,因为类方法不知道实例成员。类的实例方法也不能在类方法中调用,除非在该类的实例上调用它们。

Instance methods

实例方法

on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword. Instance methods operate on specific instances of classes. Instance methods are not declared as static.

另一方面,在调用类之前,需要一个类的实例存在,因此需要使用new关键字创建一个类的实例。实例方法对类的特定实例进行操作。实例方法没有声明为静态方法。

#12


3  

In Objective-C all methods start with either a "-" or "+" character. Example:

在Objective-C中,所有方法都以“-”或“+”字符开头。例子:

@interface MyClass : NSObject
// instance method
- (void) instanceMethod;

+ (void) classMethod;
@end

The "+" and "-" characters specify whether a method is a class method or an instance method respectively.

“+”和“-”字符分别指定方法是类方法还是实例方法。

The difference would be clear if we call these methods. Here the methods are declared in MyClass.

如果我们称这些方法为方法,区别就很明显了。这里的方法在MyClass中声明。

instance method require an instance of the class:

实例方法需要类的实例:

MyClass* myClass = [[MyClass alloc] init];
[myClass instanceMethod];

Inside MyClass other methods can call instance methods of MyClass using self:

在MyClass内部,其他方法可以使用self调用MyClass的实例方法:

-(void) someMethod
{
    [self instanceMethod];
}

But, class methods must be called on the class itself:

但是,类方法必须在类本身上调用:

[MyClass classMethod];

Or:

或者:

MyClass* myClass = [[MyClass alloc] init];
[myClass class] classMethod];

This won't work:

这不会工作:

// Error
[myClass classMethod];
// Error
[self classMethod];

#13


3  

CLASS METHODS


A class method typically either creates a new instance of the class or retrieves some global properties of the class. Class methods do not operate on an instance or have any access to instance variable.

类方法通常会创建类的新实例或检索类的一些全局属性。类方法不操作实例或对实例变量有任何访问权。


INSTANCE METHODS


An instance method operates on a particular instance of the class. For example, the accessors method that you implemented are all instance methods. You use them to set or get the instance variables of a particular object.

实例方法对类的特定实例进行操作。例如,您实现的访问器方法都是实例方法。您可以使用它们来设置或获取特定对象的实例变量。


INVOKE


To invoke an instance method, you send the message to an instance of the class.

要调用实例方法,请将消息发送到类的实例。

To invoke a class method, you send the message to the class directly.

要调用类方法,可以直接将消息发送给类。


Source: IOS - Objective-C - Class Methods And Instance Methods

源:IOS - Objective-C - Class方法和实例方法

#14


1  

Class methods can't change or know the value of any instance variable. That should be the criteria for knowing if an instance method can be a class method.

类方法不能改变或知道任何实例变量的值。这应该是判断实例方法是否可以是类方法的标准。

#15


1  

Also remember, the same idea applies to variables. You will come across terms like static, member, instance, class and so on when talking about variables the same as you would for methods/functions.

记住,同样的道理也适用于变量。在讨论变量时,您将遇到静态、成员、实例、类等术语,就像您在讨论方法/函数时遇到的那样。

It seems the common term in the Obj-C community is ivar for instance variable, but I am not an Obj-C guy, yet.

似乎object - c社区中常见的术语是ivar,例如变量,但我还不是object - c。

#16


1  

An update to the above answers, I agree instance methods use an instance of a class, whereas a class method can be used with just the class name.

对以上答案的更新,我同意实例方法使用类的实例,而类方法只能使用类名。

There is NO more any difference between instance method & class method after automatic reference counting came to existence in Objective-C.

在Objective-C中出现自动引用计数后,实例方法和类方法没有任何区别。

For Example[NS StringWithformat:..] a class method & [[NSString alloc] initwihtformat:..] an instance method, both are same after ARC

例如[NS StringWithformat:. .一个类方法& [[NSString alloc] initwihtformat:..]一个实例方法,在圆弧之后都是一样的

#17


1  

Note: This is only in pseudo code format

注意:这只是伪代码格式。

Class method

类方法

Almost does all it needs to do is during compile time. It doesn't need any user input, nor the computation of it is based on an instance. Everything about it is based on the class/blueprint——which is unique ie you don't have multiple blueprints for one class. Can you have different variations during compile time? No, therefore the class is unique and so no matter how many times you call a class method the pointer pointing to it would be the same.

它所需要做的几乎都是在编译期间。它不需要任何用户输入,也不需要基于实例进行计算。它的一切都基于类/蓝图——这是唯一的(一个类没有多个蓝图)。你能在编译期间有不同的变化吗?不,所以这个类是唯一的所以不管你调用了多少次类方法指针指向它的指针都是一样的。

PlanetOfLiving: return @"Earth" // No matter how many times you run this method...nothing changes.

Instance Method

实例方法

On the contrary instance method happens during runtime, since it is only then that you have created an instance of something which could vary upon every instantiation.

相反的实例方法在运行时发生,因为只有这样,您才创建了一个实例,该实例在每个实例化时都可能发生变化。

initWithName: @"John" lastName: @"Doe"Age:12 @"cool"
initWithName: @"Donald" lastName: @"Drumpf"Age:5 attitude:@"He started"
initWithName: @"President" lastName: @"Obama"Age:54 attitude: @"Awesome"
//As you can see the value can change for each instance.

If you are coming from other languages Static methods are same as class methods.
If you are coming from Swift, type methods are same as class methods.

如果您来自其他语言,静态方法与类方法相同。如果您来自Swift,类型方法与类方法相同。

#18


0  

Adding to above answers

增加以上的答案

Class method will work on class, we will use this for general purpose where like +stringWithFormat, size of class and most importantly for init etc

类方法将在类上使用,我们将使用它来实现一般用途,例如+stringWithFormat、类大小,最重要的是init等。

NSString *str = [NSString stringWithFormat:@"%.02f%%",someFloat];

NSString *str = [NSString stringWithFormat:@"%.02f% ",someFloat];

Instance Method will work on an instance of a class not on a class like we are having two persons and we want to get know the balance of each separately here we need to use instance method. Because it won't return general response. e.g. like determine the count of NSSArray etc.

实例方法将在一个类的实例上工作,而不是像我们这样有两个人的类,我们想要知道每个单独的平衡,我们需要使用实例方法。因为它不会返回一般的响应。例如确定NSSArray的计数等。

[johnson getAccountBalance];

[约翰逊getAccountBalance];

[ankit getAccountBalance];

[ankit getAccountBalance];