6

BNRItemStore是一个单身人士,我对为什么super allocWithZone:必须调用而不是普通的 old感到困惑super alloc。然后覆盖alloc而不是allocWithZone.

#import "BNRItemStore.h"

@implementation BNRItemStore

+(BNRItemStore *)sharedStore {
    static BNRItemStore *sharedStore = nil;

    if (!sharedStore)
        sharedStore = [[super allocWithZone: nil] init];

    return sharedStore;
}

+(id)allocWithZone:(NSZone *)zone {
    return [self sharedStore];
}

@end
4

2 回答 2

10

[super alloc]将调用 to allocWithZone:,您已将其覆盖以执行其他操作。为了真正获得超类的实现allocWithZone:(这是您想要的)而不是覆盖的版本,您必须allocWithZone:显式发送。

super关键字表示与 ; 相同的对象self。它只是告诉方法分派机制开始在超类而不是当前类中寻找相应的方法。

因此,[super alloc]将上升到超类,并在那里得到实现,它看起来像:

+ (id) alloc
{
    return [self allocWithZone:NULL];
}

在这里,self仍然代表您的自定义类,因此,您的覆盖allocWithZone:运行,这将使您的程序进入无限循环。

于 2012-08-15T01:20:13.437 回答
3

来自苹果的文档

这种方法的存在是出于历史原因;Objective-C 不再使用内存区域。

于 2013-10-11T07:39:34.433 回答