Home  >  Q&A  >  body text

objective-c - 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>
迷茫迷茫2761 days ago406

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-04-21 11:18:58

    This is NSObject Class source code

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

    Refer to this link, because your singleton’s root class may not be nsobject, so use NSAllocateObject directly.

    NSProxy is the root class, but it is under cocoa.

    The root class under iOS is NSObject, which is the root class, for reference.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-21 11:18:58

    Because some singleton implementations will override the +allocWithZone: method and return the singleton directly. This is the implementation given in Apple's documentation. So you have to use NSAllocatObject to create objects

    reply
    0
  • 高洛峰

    高洛峰2017-04-21 11:18:58

    I also had this question, and now I have this answer. There is only one copy of the uniqueInstance variable, and the subclass is shared with the parent class. If the parent class is created first, the subclass [Child alloc] or [Child sharedInstance] will return the parent class. An instance of the class, because the Singleton class overrides the allocWithZone method, and this method returns a uniqueInstance. I don’t know, right?

    reply
    0
  • Cancelreply