Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Obj-C_Singleton.m example code
//
// Common Objective-C Singleton Class.m
// iOS
//
// Created by yangboz on 03-25-14.
// Copyright (c) 2013年 GODPAPER. All rights reserved.
//
#import "App42_API_Utils.h"
@implementation App42_API_Utils
//It declares a static instance of your singleton object and initializes it to nil.
static App42_API_Utils *sharedInstance = nil;
static ServiceAPI *serviceAPIobj = nil;//Your static instance
//In your class factory method for the class (named something like “sharedInstance” or “sharedManager”), it generates an instance of the class but only if the static instance is nil.
+(App42_API_Utils *)sharedInstance
{
if (sharedInstance==nil) {
sharedInstance = [[super allocWithZone:NULL] init];
//
serviceAPIobj = [[ServiceAPI alloc] init];
}
//
return sharedInstance;
}
//It overrides the allocWithZone: method to ensure that another instance is not allocated if someone tries to allocate and initialize an instance of your class directly instead of using the class factory method. Instead, it just returns the shared object.
+(id)allocWithZone:(NSZone *)zone
{
return [ [self sharedInstance] retain];
}
//It implements the base protocol methods copyWithZone:, release, retain, retainCount, and autorelease to do the appropriate things to ensure singleton status. (The last four of these methods apply to memory-managed code, not to garbage-collected code.)
-(id)copyWithZone:(NSZone *)zone
{
return self;
}
-(id)retain
{
return self;
}
-(NSUInteger)retainCount
{
return NSUIntegerMax;//denotes an object that cannot be released.
}
//-(void)release
//{
// //do nothing.
//}
//implementations
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.