Reputation: 11297
I am somewhat new to iOS 5 singletons and am using a singleton as documented here:
Something like this:
MyManager.h
#import <Foundation/Foundation.h>
@interface MyManager : NSObject
//Data for section 1
@property(nonatomic,copy) NSString * section1a;
@property(nonatomic, assign) NSUInteger section1b;
//Data for section 2
@property(nonatomic,copy) NSString * section2a;
@property(nonatomic, assign) NSUInteger section2b;
+ (id)sharedInstance;
@end
MyManager.m
@implementation MyManager
@synthesize section1a, section1b, section2a; , section2b;
+ (id)sharedInstance
{
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init]; // or some other init method
});
return _sharedObject;
}
@end
So I use it as follows:
MyManager * myManager = [MyManager sharedInstance];
myManager.data = self.data
Is this how you generally use the singleton? Am I missing anything? Sorry for the basic questions I just want to make sure I am doing it right.
Thanks
Upvotes: 2
Views: 192
Reputation: 3915
Refer to this: Singleton in iOS 5? You should override allowWithZone to prevent rogue code from creating a new instance.
Upvotes: 0
Reputation: 9335
You're doing it right. This is (currently :) the way to go and works fine with ARC enabled, multiple threads etc.
It isn't strictly a singleton, as you can alloc more instances of the class, but I don't think that's relevant in your case.
Upvotes: 1
Reputation: 11320
I usually make my singleton as such (suppose we are making a singleton for Manager):
static (Manager *) instance;
+ (Manager *) getInstance
{
if(!instance) instance = [[Manager alloc] init];
return instance;
}
This is a very basic singleton (it doesn't take into account multithreading or other advanced features) but this is the basic format.
Upvotes: 0