Objective C 对象分配和释放

Objective C object alloc and release

我是 objective C 的新手。我想知道为什么有些 classes 在构建对象时不需要 alloc。例如,class NSNumber。要构建一个对象:

NSNumber * strangeNum;
strangeNum = [NSNumber numberWithInteger:100];

不需要 alloc 也不需要 release

但是如果我自己定义一个class,说myClass然后构建一个对象。我需要

myClass * myObj=[[myClass alloc] init];
...
[myObj release] // if without ARC

有人可以详细解释一下吗?非常感谢。

实际上 NSNumber 确实需要分配,但您使用的是执行分配的静态方法。

如果你要看 NSNumber 的源代码,它的 numberWithInteger 的静态方法(非实例方法)可能是这样的

-(NSNumber)numberWithInteger:(int)intVal {
   NSNumber num = [[NSNumber alloc] init];
   *Some magic*
}

基本上,Apple 刚刚为您简化了一些操作。

release 方法几乎已被 ARC(自动引用计数)淘汰,并且您很少(如果有的话)遇到更新的(过去几年)代码。要理解为什么不对从 numberWithInteger: 获得的对象调用 release,您需要阅读 Objective-C 的内存管理策略,目前可以在 [=17] 找到=].

alloc 方法是一种 class 方法,是为 NSObject 派生的任何 class 分配内存的规范方法。 类 可能有任意数量的 class 方法,并且 class 方法可以代表您创建一个对象。在方法调用链中的某个地方,alloc 将被调用,只是对于 Foundation classes,你没有源代码,你看不到它。

第一个案例 - +[NSNumber numberWithInteger:]。这是一个 class 工厂方法。来自 Apple documentation:

Class factory methods should always start with the name of the class (without the prefix) that they create, with the exception of subclasses of classes with existing factory methods. In the case of the NSArray class, for example, the factory methods start with array. The NSMutableArray class doesn’t define any of its own class-specific factory methods, so the factory methods for a mutable array still begin with array.

Class 工厂方法 return 自动释放对象。通常它被用作一个简单的快捷方式,调用相应的 init 方法:

+ (NSNumber)numberWithInteger:(int)intVal {
    return [[[self alloc] initWithInteger:intVal] autorelease];
}

第二种情况是 NSNumber 实例的显式创建。因为您没有在创建实例后立即调用 autorelease,所以您应该在使用完对象释放分配的内存后调用 release

因此,在这两种情况下,对象实例都是通过 allocinit 调用序列构建的。