-1

I am doing the following in order to initialise my singelton:

ChatDataController *box = [ChatDataController sharedInstance];

The problem is that i use *box in different places, for example in these methods:

- (void) viewDidAppear:(BOOL)animated
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

Is there a way to only have to initialise once? so that *box can be used in any method within a given class?

Alosyius
  • 8,771
  • 26
  • 76
  • 120

4 Answers4

1

Put this code in your ChatDataController

+ (ChatDataController *)sharedInstance
{
    static ChatDataController *object = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        object = [[ChatDataController alloc] init];
    });
    return object;
}
iNeal
  • 1,729
  • 15
  • 23
0

Is there a way to only have to initialise once?

If ChatDataController is a singleton it can only be initialised once.

[ChatDataController sharedInstance] should always return the same instance and only alloc] init] the first time it is called.

If, as you mentioned in one of the comments, you already have your singleton, then simply call [ChatDataController sharedInstance] whenever you need the shared instance. There is no need to store the pointer to the object in a property.

Sebastian
  • 7,670
  • 5
  • 38
  • 50
  • I have given +1 to this answer as I believe it doesn't deserve a -1 as it is correct and informative. – Popeye Dec 13 '13 at 08:33
-1

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html

In "Creating a Singleton Instance"

static MyGizmoClass *sharedGizmoManager = nil;

+ (MyGizmoClass*)sharedManager
{
    if (sharedGizmoManager == nil) {
        sharedGizmoManager = [[super allocWithZone:NULL] init];
    }
    return sharedGizmoManager;
}
johnyu
  • 2,152
  • 1
  • 15
  • 33
-1

try this one:- create macro in .pch file

first import class

#import"ChatDataController.h"

then create macro (sharedInstance must be class method)

#define box ([ChatDataController sharedInstance]) 

after that u you can use this object in all classes

Chaman Sharma
  • 641
  • 5
  • 10