Objective-C 中实例方法与类方法的目的 [英] Purpose of Instance Methods vs. Class Methods in Objective-C

查看:20
本文介绍了Objective-C 中实例方法与类方法的目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经检查了所有这些问题...

I have checked out all these questions...

...他们所解释的只是在向类发送消息时如何在类的实例上使用实例方法,以及如何将类方法与类一起使用.这很有帮助,但我很想知道为什么人们会使用类方法与实例方法.

...and all they explain is how instance methods are used on instances of a class and class methods are used with the class, when a message is sent to a class. This is helpful, but I'm curious to know why one would use a class method vs. an instance method.

推荐答案

一般来说,当您需要对对象的特定实例进行操作的代码时,您应该创建实例方法.当您需要执行一般涉及该类但可能不对该类的任何特定对象进行操作的操作时,您可以创建一个类方法.

Generally speaking, you should create instance methods when you need code that operates on a specific instance of an object. You create a class method when you need to do something that involves that class in general but probably doesn't operate on any specific objects of that class.

在实践中,您会发现几乎所有的方法都应该是实例方法.看看任何现有的 Objective-C 类,如 NSStringNSArrayUIView 等,你会发现绝大多数他们的方法中有很多是实例方法.类方法最常见的用途(再看看我提到的类)是为了方便构造函数返回 autorelease 对象,或单例访问器.

In practice, you will find that nearly all of your methods should be instance methods. Just take a look at any existing Objective-C class like NSString, NSArray, UIView, etc. and you'll see that the vast majority of their methods are instance methods. The most common use of class methods (again, look at the classes I mentioned) are for convenience constructors that return autorelease objects, or singleton accessors.

考虑NSString 中的length 方法.为什么这是一个实例方法而不是类方法?它是一个实例方法,因为只有询问 NSString 的特定实例它的长度是多少才有意义.一般向 NSString 询问长度(即如果 length 是一个类方法)没有任何意义.

Consider the length method in NSString. Why is this an instance method and not a class method? It is an instance method because it only makes sense to ask a specific instance of NSString what its length is. Asking NSString in general for a length (i.e. if length was a class method) wouldn't make any sense.

另一方面,假设我们要向 NSNumber 添加一个方法,该方法将返回可以存储在给定系统上的最大整数值.在这种情况下,它应该是一个类方法,因为我们只是问一个独立于任何特定实例的NSNumber的一般问题.

On the other hand, let's say that we want to add a method to NSNumber that will return the maximum integer value that can be stored on a given system. In this case, it should be a class method because we're just asking a general question of NSNumber that is independent of any specific instance.

这篇关于Objective-C 中实例方法与类方法的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆