我需要一个好的类比来理解类方法与实例方法

问题描述:

作为书的阅读,我得到相当困惑深入到NSNumber类和谈论所有不同的方法,你可以调用它。我有几个问题:

Im getting fairly confused as the book im reading is delving into the NSNumber class and talks about all the different methods you can call on it. I have a couple questions:

1。)你不必在基础类上调用典型的alloc或init?

1.) Do you not have to call a typical alloc or init on foundation classes?

2.)在什么情况下,你会使用,比如说,numberWithChar:相对于initWithChar(我认为这是部分,是困扰我最多,不是真的确定im groking这个概念在我需要的水平

2.)in what cases would you use, say, numberWithChar: as opposed to initWithChar (i think this is the part that is messing me up the most, not really sure im groking this concept on the level i need to be, if you folks could break it down for me I think it would really help me get over this humper-roo.

谢谢你,

Nick

类/实例类比



类是类型房子的蓝图实例就像实际的房子所以你只能有一个房子的类型的一个蓝图,但你可以有多个相同类型的实际房子。此外,你可以有多个蓝图,并且每个蓝图描述了不同类型的房子。

Class/Instance Analogies

Classes are like blueprints for a type house. Instances are like actual houses. So you can only have one blueprint for a single type of house, but you can have multiple actual houses of the same type. Also, you can have multiple blueprints, and each blueprint describes a different type of house.

您可以使用的另一个类比是类似于cookie切割器,实例类似于cookie切割器。

Another analogy you can use is that classes are like cookie cutters, and instances are like cookies made from a cookie cutter.

代码中每个类都有一个类对象 。要引用类对象,只需使用类名。 alloc 是分配一个新实例的类方法:

There is one "class object" for every class in your code. To refer to the class object, you just use the class name. alloc is a class method that allocates a new instance like so:

MyWidget * w = [MyWidget alloc];

但是, alloc 不初始化类,因此不会设置任何成员变量。 init 是一个实例方法,将初始化新分配的实例。所以要分配和初始化一个新的实例,你这样做:

However, alloc doesn't initialize the class, so none of the member variables will be set up. init is an instance method that will initialize a newly allocated instance. So to allocate and initialize a new instance, you do this:

MyWidget * w = [[MyWidget alloc] init];

这相当于:

MyWidget* w = [MyWidget alloc]; //alloc is being called on the class
w = [w init]; //init is being called on the instance

另一个常见类型的类方法是类似 numberWithChar:。这基本上是 numberWithChar:所做的:

Another common type of class method is a factory method like numberWithChar:. This is basically what numberWithChar: does:

+(NSNumber*) numberWithChar:(char)c;
{
    return [[[NSNumber alloc] initWithChar:c] autorelease];
}

唯一的区别是 numberWithChar: code>返回一个自动释放的对象。

The only real difference is that numberWithChar: returns an autoreleased object.

所有对象必须被分配和初始化。其中包括基础类。

All objects must be allocated and initialized. That includes foundation classes.