类方法和实例方法说明

发布于 2024-11-28 19:50:43 字数 65 浏览 5 评论 0原文

到目前为止,我想知道这两者之间的区别。我一直在使用实例方法,但不知道其背后的含义。谁能用最简单的方式解释一下?谢谢。

Until now, I would like to know the difference between these 2. I always been using instance methods but have no idea the meaning behind it. Can anyone explain in the simplest way? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

请爱~陌生人 2024-12-05 19:50:43

类方法在类本身上调用,如下所示:

[NSDate date];
// declared as: + (NSDate *)date;

在实际对象上调用实例方法:

NSDate *date = ...;
[date timeIntervalSinceNow];
// declared as: - (NSTimeInterval)timeIntervalSinceNow;

阅读 Objective-C 编程语言指南更多信息。

Class methods are called on the classes themselves, like this:

[NSDate date];
// declared as: + (NSDate *)date;

Instance methods are called on actual objects:

NSDate *date = ...;
[date timeIntervalSinceNow];
// declared as: - (NSTimeInterval)timeIntervalSinceNow;

Read the The Objective-C Programming Language guide for more information.

仙女山的月亮 2024-12-05 19:50:43

可以在不创建类实例的情况下使用类方法。
由于您没有此类的实例,因此您无法使用任何类实例变量。

例如:

@implementation MyStringHelper


@synthesize lastChecked;

+ (BOOL) checkIfEmptyString:(NSString *)checkString {
  return ([checkString length] == 0);
}
@end

因此您可以这样调用:

if ( [MyStringHelper checkIfEmptyString:@"NotEmprty"] ) {
// do something
}

但是您不能使用属性 latChecked 因为这需要 MyStringHelper 类的实例。

Well class methods can be used without making an instance of a class.
Since you don't have an instance of this class you can't use any class instance variables.

ex:

@implementation MyStringHelper


@synthesize lastChecked;

+ (BOOL) checkIfEmptyString:(NSString *)checkString {
  return ([checkString length] == 0);
}
@end

Thus you can call this like:

if ( [MyStringHelper checkIfEmptyString:@"NotEmprty"] ) {
// do something
}

But you can't use the properties latChecked because this will need an instance of the MyStringHelper class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文