0

I have a custom NSObject class, with my array in for my data which I want to use etc. But how can I alloc and init this class object, and use it everywhere without always using: CustomClass class = [[CustomClass alloc] init]; because this makes an object every time from my class, so the data is totally off.

I am always getting things about how to alloc/init something but nothing about on how to handle a class that says in the memory and you can use each time without making a new one trough all your other classes.

Kets
  • 438
  • 2
  • 8
  • 24

2 Answers2

5

Read up about singletons or shared instances. Here is the currently most agreed upon version:

+ (MyClass *)sharedInstance {

    static MyClass *sharedInstance;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken,^{

        sharedInstance=[[MyClass alloc]init];
    });

    return sharedInstance;
}

Now MyClass.sharedInstance (or [MyClass sharedInstance] for old syntax) will give you a single shared instance of your class. The dispatch_once stuff is to make it thread safe. Obviously you need to replace MyClass with the name of your class.

Gerd K
  • 2,933
  • 1
  • 20
  • 23
  • 2
    Many peoply prefer to use the "dot syntax" only for *properties* (but there are different opinions), but I would not call `[MyClass sharedInstance]` the "old syntax". – Martin R May 09 '14 at 13:55
  • Yeah, obviously that I need to change the name of "MyClass" haha, thanks for the information! Going to read up a bit more about those things! – Kets May 09 '14 at 13:56
  • @Martin R: true. But it is less typing and faster to read, so I have been using it more and more for cases like that as well. Though I do not have a strong preference either way. – Gerd K May 09 '14 at 13:59
0

You need to use a Singleton pattern as explained in this answer Correct Singleton Pattern Objective C (iOS)? Only one instance of the class runs and can be used throughout your code.

Community
  • 1
  • 1
  • That code is significantly outdated and should not be copied. Gerd's code works absolutely fine and reliably. And doesn't work with ARC, which is what everyone is using nowadays. – gnasher729 May 09 '14 at 14:08