What does the Singleton example actually do in the Apple documentation?

Can someone explain to me a few things regarding the implementation of Singleton in the Apple documentation.

Link: - http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html

Go to Create a Singleton instance in the link.

I tried, but could not understand a few things: -

  • What does [super allocWithZone: NULL] do in + (MyGizmoClass *) sharedManager.?
  • Why does allocWithZone call the sharedManger method and return a save call to its return type when it saves itself?
  • If Singleton has any instance variables, where should they be initialized?

If anyone can briefly explain how the allocWithZone and sharedManager methods work, many of these questions will be answered automatically.

+4
source share
2 answers

This implementation is usually considered over_kill. There are many protection measures against a programmer trying to misuse a singleton, which is not usually considered necessary.

Here is an example of a simpler implementation from Yoga :

+ (id)sharedFoo { static dispatch_once_t once; static MyFoo *sharedFoo; dispatch_once(&once, ^ { sharedFoo = [[self alloc] init]; }); return sharedFoo; } 
+2
source

Here - I rephrased your questions:

What does [super allocWithZone:NULL] do?

This is the same as saying [super alloc] . The withZone part is related to where your object will be stored in memory. In practice, it would be very rare to use it. See this question for more information - what is the difference between alloc and allocWithZone :?

Why the retain method returns itself (and does not increment the save counter)

Singletones persist throughout the life of your application β€” you don’t care about the hold account, because there is no situation in which you would like to release your singleton. retain returns self as politeness and agreement (and allow nested expressions).

If Singleton has some instance variables in it, where should they be initialized?

To you. You usually initialize them in the init method, as in a regular object.

+2
source

Source: https://habr.com/ru/post/1390051/


All Articles