类方法和实例方法之间的区别?
所有其他答案似乎已被错误的标记已被捕获,现在已被修复。
在Objective-C中,实例方法是当消息发送到类的实例时调用的方法。因此,例如:
id foo = [[MyClass alloc] init];
[foo someMethod];
// ^^^^^^^^^^ This message invokes an instance method.
在Objective-C,类本身的对象和类方法是简单地当一个消息被发送给一个类对象时调用的方法。即
[MyClass someMethod];
// ^^^^^^^^^^ This message invokes a class method.
注意,在上述实施例的选择器是相同的,但因为在一个情况下,它被发送到MyClass的的实例,并在它被发送到MyClass的另一种情况下,不同的方法被调用。在接口声明中,你可能会看到:
@interface MyClass : NSObject
{
}
+(id) someMethod; // declaration of class method
-(id) someMethod; // declaration of instance method
@end
,并在实施
@implementation MyClass
+(id) someMethod
{
// Here self is the class object
}
-(id) someMethod
{
// here self is an instance of the class
}
@end
编辑
对不起,错过了第二部分。这样没有优点或缺点。这就好比问什么是时间和时间,以及相对于另一方的优点有什么区别。这是没有意义的,因为它们是为不同的目的而设计的。
类方法最常见的用途是在需要时获取实例。 +alloc
是一种为您提供新的未初始化实例的类方法。 NSString有许多类方法可以为你提供新的字符串,例如+ stringWithForma
另一个常见用途是获得一个单例如
+(MyClass*) myUniqueObject
{
static MyUniqueObject* theObject = nil;
if (theObject == nil)
{
theObject = [[MyClass alloc] init];
}
return theObject;
}
上述方法也可以作为实例方法使用,因为object是静态的。但是,如果将其设置为类方法并且不必首先创建实例,则语义更清晰。
静态成员函数被非正式地称为类方法(不正确)。在C++中没有方法,有成员函数。
我不知道我们是否可以谈任何优势,这是相当要实现什么样的问题。
实例方法适用于类的实例,因此他们需要一个对象上应用,可以访问他们的主叫方的成员:
Foo bar;
bar.instanceMethod();
在另一方面类方法适用于整个类,他们不” t依赖于任何对象:
Foo::classMethod();
如果我们不希望创建类的对象,然后我们使用类方法 如果我们想通过一个类的对象调用该方法,然后我们使用实例方法
类方法与类,但实例方法使用与该类即实例
//Class method example
className *objectName = [[className alloc]init];
[objectName methodName];
//Instance method example
[className methodName];
实例方法使用一个类的实例的对象所使用的,而类方法可以只用类名被使用。在类方法之前使用+符号,其中在实例变量之前使用单个desh( - )。
@interface MyClass : NSObject
+ (void)aClassMethod;
- (void)anInstanceMethod;
@end
它们也可以使用像这样,
[MyClass aClassMethod];
MyClass *object = [[MyClass alloc] init];
[object anInstanceMethod];
或另一个例子是:
[
NSString string]; //class method
NSString *mystring = [NSString alloc]init];
[mystring changeText]; //instance Method
像大多数其他的答案都表示,实例方法使用一个类的实例,而类方法只能与类名一起使用。在Objective-C他们正是如此定义:
@interface MyClass : NSObject
+ (void)aClassMethod;
- (void)anInstanceMethod;
@end
然后,他们可以使用像这样:
// class methods must be called on the class itself
[MyClass aClassMethod];
// instance method require an instance of the class
MyClass *object = [[MyClass alloc] init];
[object anInstanceMethod];
的类方法的一些真实世界的例子有很多基础类的便利方法,如NSString
的+stringWithFormat:
或NSArray
的+arrayWithArray:
。实例方法将是NSArray
的-count
方法。
你真的在谈论C++吗?我们不使用术语“实例方法”和“类方法”;我们使用术语“(非静态)成员函数”和“静态成员函数”。 – 2010-12-07 10:10:21