totalitarian
totalitarian

Reputation: 3666

Pointer to existing object?

Ok so I have a class that I init like so in QuickNoteNotesDataController.m

QuickNoteNotesDataController *dataController = [[QuickNoteNotesDataController alloc] init];

Then I need to be able to access the same instance of this class from another file QuickNoteDetailViewController.m

How do I get a pointer to the same instance without calling alloc init again and creating a new instance?

Upvotes: 0

Views: 101

Answers (3)

Johannes Lund
Johannes Lund

Reputation: 1917

You could go with a singleton if you only need one instance:

//In QuickNoteNotesDataController.m
static QuickNoteNotesDataController *sharedInstance;
+ (id)sharedDataController {
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedInstance = [[QuickNoteNotesDataController alloc] init];
    });
    return sharedInstance;
}

Otherwise you could create a property in the QuickNoteDetailViewController

@property (nonatomic, strong) QuickNoteNotesDataController *dataController

and set the dataController you already have to the property when you create the detailViewController.

Upvotes: 1

MrWaqasAhmed
MrWaqasAhmed

Reputation: 1489

You can make your QuickNoteNotesDataController class as Singleton,by then you can share single instance of this class in whole app.

Upvotes: 1

Anoop Vaidya
Anoop Vaidya

Reputation: 46543

Same instance from other class : you need to create a shared instance.

Or a static property for this.

But do not go with extern variable.

Upvotes: 1

Related Questions