allocWithZone和NSAllocateObject的区别是什么?

《Objective-C编程之道》“第7章单例”中提到用NSAllocateObject来分配可以防止子类分配时候得到父类的对象。

但是据我测试没有任何区别,请知情人士指点。

创建对象代码
+ (Singleton *)sharedInstance
{
  if (uniqueInstance == nil) {
    uniqueInstance = [[super allocWithZone:nil] init];
//    uniqueInstance = NSAllocateObject([self class], 0, nil);
  }
  return uniqueInstance;
}
测试代码
id child1 = [[Child alloc] init];
NSLog(@"child1 = %@", child1);
    
id child2 = [[Child alloc] init];
NSLog(@"child2 = %@", child2);
测试结果
2013-03-22 16:59:34.634 Singleton[5107:303] This is Singleton demo.
2013-03-22 16:59:34.636 Singleton[5107:303] child1 = <Child: 0x10010a9b0>
2013-03-22 16:59:34.637 Singleton[5107:303] child2 = <Child: 0x10010a9b0>
阅读 7.6k
3 个回答

这是NSObject Class源码

+ (id) allocWithZone:(NSZone*)z
{
  return NSAllocateObject(self, 0, z);
}

参考这个链接,因为你的singleton可能root class不是nsobject,所以直接使用NSAllocateObject.

NSProxy就是root class,但是它是cocoa下的。

iOS下的root class就是NSObject就是root class,参考

因为一些单例的实现会覆盖 +allocWithZone: 方法,直接返回该单例,苹果文档中给出的实现就是这样。所以你要用 NSAllocatObject 来创建对象

新手上路,请多包涵

我也有此一问,现在有了这个答案,uniqueInstance变量只有一份,并且子类与父类共享,如果先创建了父类,子类[Child alloc]或者[Child sharedInstance]均返回的是父类的实例,因为Singleton类重写了allocWithZone方法,且此方法返回的是uniqueInstance。不知道对不对?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进