《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>
巴扎黑2017-04-21 11:18:58
これはNSObjectクラスのソースコードです
リーリーこのリンクを参照してください。シングルトンのルートクラスは nsobject ではない可能性があるため、NSAllocateObject を直接使用してください。
NSProxy はルートクラスですが、cocoa の下にあります。参考までに、iOS のルート クラスはルート クラスである NSObject です。
伊谢尔伦2017-04-21 11:18:58
一部のシングルトン実装は +allocWithZone: メソッドをオーバーライドしてシングルトンを直接返すため、これは Apple のドキュメントに記載されている実装です。したがって、オブジェクトを作成するには NSAllocatObject を使用する必要があります
高洛峰2017-04-21 11:18:58
私もこの質問をしましたが、現在、この答えが得られています。 uniqueInstance 変数のコピーは 1 つだけあり、親クラスが最初に作成された場合、サブクラスは [Child alloc] または [ Singleton クラスは allocWithZone メソッドをオーバーライドし、このメソッドは uniqueInstance を返すため、子 [sharedInstance] は親クラスのインスタンスを返します。分からないですよね?