Frage

I have seen in a lot of standard Apple APIs and open source, custom APIs that an object can be declared as shared. For example, NSUserDefaults is accessible by the method [NSUserDefaults standardUserDefaults] and NSNotificationCenter by [NSNotificationCenter defaultCenter]. I was wondering how I could make one of my custom objects in an application shared, so the current instance of that object could be accessed via a method like [MyObject sharedObject]?

I downloaded an application with this functionality, but the object that was shared only declared the method used to access the current instance of the object in the header file (.h), and there was no implementation of the method in the implementation file (.m).

It declared it by saying:

+ (GameObject *)sharedGameObject;

I know the plus means it is a class method, meaning that it does not require an instance of that class to be created, but can be accessed anyway, like CALayer's [CALayer layer] method.

I would appreciate any help! Thanks,

Ben

War es hilfreich?

Lösung

Do like this:

static id shared = NULL;
+ (id)sharedInstance
{
    @synchronized(self) {
        if (shared == NULL)
        {
            shared = [[self alloc] init];
        }
    }
    return shared;
}

By the way, [CALayer layer] is NOT for accessing a shared layer object. It creates a new, autoreleased CALayer instance.

Andere Tipps

The design pattern you are referring to is called Singleton, and you'll be able to find a lot of information on this now that you know what to search for. There are a great many ways of implementing this pattern in Objective-C, and in fact the most useful in my opinion isn't actually technically a singleton.

It’s called a Singleton pattern and in my opinion it’s not a good idea design-wise (the Apple examples notwithstanding). Here’s some rationale against singleton misuse and here’s a sample Xcode project showing how to share objects without singletons.

Apple recommends using dispatch_once for proper thread-safe allocation of singletons

+ (MyObject*) sharedObject {
    static MyObject* sharedInstance;
    static dispatch_once_t once;
    dispatch_once(&once, ^ {
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

You are searching for a Design-Pattern called Singleton Wiki . It is made from the Gang of Four (GOF)Wiki and helps to stay objects alive and accessible through other instances. There are already templates which you could use: Template

The MVC-Pattern could do your job aswell, just init the

Appdelegate.h

Appdelegate.h

@property (strong, nonatomic) GameObject *sharedGameObject;

Appdelegate.m

@synthesize sharedGameObject;

in the ApplicationsDelegate and access it by using the

Application Delegate

YourClass

Yourclass.m

myAppDelegate *delegate = [[UIApplication sharedApplication] delegate]; user = delegate.sharedGameObject;

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top