Monday, January 13, 2014

Why write a singleton class method to create a class object?

This is a singleton class NetAccess class methods defined and implemented to create the object.
+ (NetAccess *) sharedNetAccess
{
if (! _sharedNetAccess)
{
_sharedNetAccess = [[NetAccess alloc] init];
}
return _sharedNetAccess;
}
I do not know, why not use local direct NetAccess * myNet = [NetAccess alloc] init];?
Reply:
More conventional writing is like this:
+ (NetAccess *) sharedNetAccess
{
static NetAccess * sharedNetAccess;
static dispatch_once_t onceToken;
dispatch_once (& onceToken, ^ {
sharedNetAccess = [[NetAccess alloc] init];
});
return sharedNetAccess;
}

Singleton, by definition, there is only a unique instance, is a static instance, that whatever you call [NetAccess sharedNetAccess] in Class A Class B or Class C; its address is the same.
Do like this is very convenient place, such as a plastic which has a variable a, you first assigned to the class A 5, and then called in the class B, its value is 5.
Reply:
Static initialization only once instance, the wording of the landlord can refer upstairs. You can also write your own initialization method, disable the swap init.
Reply:
In Class A:
NetAccess * myNet = [NetAccess alloc] init];

In Class B:
NetAccess * myNet = [NetAccess alloc] init];

Will produce two different addresses NetAccess object, so the data can not reach a common purpose in the
Reply:
Ensure that only one instance of this kind in the big picture
Reply:
Upstairs answers are good, in order to ensure that only one such instance in the global
Reply:
So, thank you very much.

No comments:

Post a Comment