Amazon.com Widgets shared object manager ( Singleton )
Welcome, Guest. Please login or register.
Did you miss your activation email?
October 31, 2014, 11:01:06 PM
Home Help Search chat Login Register 
News: Read this please.The Great Kangaroo Escape Looking for reviews of the 4th ed on Amazon!   Twitter:  @skochan
                     

+ Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
|-+ Old Stuff
| |-+ Shared Code Library
| | |-+ shared object manager ( Singleton )
Pages: [1] Go Down
Print
Author Topic: shared object manager ( Singleton ) (Read 5492 times)
TotalLuck
Full Member
***
Posts: 107



WWW Email




on: November 15, 2010, 11:59:52 PM

I found this bit of code really helpful in my latest app project and thought i would post it here.

i will preface this  with  it is not my code but Matt Galloway's Code i am posting.  i modified mine to my project but this was good.

Code: (Objective-C)
#import <foundation/Foundation.h>
@interface MyManager : NSObject {

    NSString *someProperty;

}
@property (nonatomic, retain) NSString *someProperty;

+ (id)sharedManager;

@end

Code: (Objective-C)
#import "MyManager.h"

static MyManager *sharedMyManager = nil;

@implementation MyManager

@synthesize someProperty;

#pragma mark Singleton Methods
+ (id)sharedManager {
@synchronized(self) {
if(sharedMyManager == nil)
sharedMyManager = [[super allocWithZone:NULL] init];
}
return sharedMyManager;
}
+ (id)allocWithZone:(NSZone *)zone {
return [[self sharedManager] retain];
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release {
// never release
}
- (id)autorelease {
return self;
}
- (id)init {
if (self = [super init]) {
someProperty = [[NSString alloc] initWithString:@"Default Property Value"];
}
return self;
}
- (void)dealloc {
// Should never be called, but just here for clarity really.
[someProperty release];
[super dealloc];
}

@end

I dont recall anything in the  book about singletons.  Maybe steve has a word or two about when and why to use them.

Greg

Logged

Apps available on  iTunes store:
"ADACode"  iPhone and iPad versions, "ADAGuidelines" iPhone & iPad versions,  "Rehabilitation Act of 1973" for iPhone
"APokerTimer" now for iPhone http://bit.ly/h1fAJp
skochan
Administrator
Hero Member
*****
Posts: 3114







Reply #1 on: December 17, 2010, 04:37:59 PM

I didn't get into it in the text; it's a bit more advanced.  Could you post some code that uses this?   It would helpful to the readers.

Cheers,

Steve
Logged
daviddelmonte
Full Member
***
Posts: 123



WWW Email




Reply #2 on: December 17, 2010, 06:36:35 PM

Would you guys mind explaining what is going on in these methods, plus a definition (and usage) for singletons? I'm seeing these pop up in discussions all over the place..

Logged
TotalLuck
Full Member
***
Posts: 107



WWW Email




Reply #3 on: December 17, 2010, 10:59:57 PM

ok ill give it a shot here.  i know Dharma also used a singleton in his latest app so maybe he can post some code also.

To start with, i relate  the singleton as a poor-mans database.  the only thing is that the singleton is initialized once (and only once) and persists in memory until the app is terminated. So it is great for small data amounts and  variables.

wiki defines it as such :
Quote
In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

I had a need in the aPokerTimer app to  reference information from any view. passing all those variables was a big pain in the ***.
I also had to be able to save the state from any view at anytime  in order to restore state in case of  app backgrounding/termination.  This made it easy to centralize all of my data and  then call it to encode and decode the data.

so i used this:
SharedManager.h
Code: (Objective-C)


#import <Foundation/Foundation.h>


@interface SharedManager : NSObject
{
NSMutableArray *sharedActiveBlinds;
NSMutableArray *sharedMasterStructureList;
NSMutableArray *payOutArray;
int players;
int buyin;
int rebuys;
int prize;

int firstIndex;
int secondIndex;
int thirdIndex;
int mins;
int secs;
int timeCount;
BOOL timerToggle;
BOOL alertTimerActive;
int currentLevel;
BOOL didDecode;
BOOL appLoad;
}

@property (nonatomic, retain) NSMutableArray  *payOutArray,*sharedActiveBlinds, *sharedMasterStructureList;
@property (nonatomic) int players,buyin,rebuys,prize,firstIndex, secondIndex, thirdIndex, mins, secs, timeCount,currentLevel;
@property (nonatomic) BOOL timerToggle,alertTimerActive,didDecode, appLoad;

+ (SharedManager *)sharedObjects;

@end



SharedManger.m
Code: (Objective-C)
#import "SharedManager.h"


static SharedManager *sharedInstance = nil;

@implementation SharedManager

@synthesize sharedActiveBlinds,sharedMasterStructureList, payOutArray;
@synthesize firstIndex, secondIndex, thirdIndex, mins, secs,timeCount, currentLevel,players,buyin,rebuys,prize;
@synthesize timerToggle,alertTimerActive,didDecode,appLoad;

+ (SharedManager *)sharedObjects
{
@synchronized (self) {
if (sharedInstance == nil) {
[[self alloc] init]; // assignment not done here, see allocWithZone
}
}

return sharedInstance;
}

+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self) {
        if (sharedInstance == nil) {
            sharedInstance = [super allocWithZone:zone];

            return sharedInstance;  // assignment and return on first allocation
        }
    }

    return nil; //on subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (void)release
{
    //do nothing
}

- (id)autorelease
{
    return self;
}

- (NSUInteger)retainCount
{
    return NSUIntegerMax;  // This is sooo not zero
}

- (id)init
{
@synchronized(self) {
[super init];
payOutArray = [[NSMutableArray alloc]init];
sharedActiveBlinds = [[NSMutableArray alloc] init];
sharedMasterStructureList = [[NSMutableArray alloc] init];
firstIndex = 0;
secondIndex = 0;
thirdIndex = 0;
players = 0;
buyin = 0;
rebuys = 0;


return self;
}
}

@end

the only thing you really need to do is  set up your variables like normal and synthesize the accessors. set up your  variables in the init method with any defaults variables.  Once that is done you can set/get the variables from any view Controller.
you can see that i haven't altered much of the original code.

in the .h file i set a number of instance variables that i want to store data in from any view i am in.  i simple #import SharedManager.h into the required  viewController .m file and there ya go.  (standard)

in the .m file
it is creating a Static instance of the shared manager first

Code: (Objective-C)
static SharedManager *sharedInstance = nil;

To get  access to the sharedManager you  use the following.:

Code: (Objective-C)
SharedManager * sharedManager = [SharedManager sharedObjects]; 

The sharedObjects method  ( and its allocWithZone) basically  makes sure there is only instance floating around.

if you haven't already done so, you should read the  blog about singletons  by  Matt Galloway. it really  explains this better than i can.

here is an example of calling the code:
Code: (Objective-C)
#import "MainVC.h"
#import "SharedManager.h"


-(IBAction) startTimer:(id)sender
{ SharedManager *sharedManager = [SharedManager sharedObjects];


if (sharedManager.timerToggle == NO)
{
sharedManager.alertTimerActive = YES;

timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self   selector:@selector (updateLabels:)   userInfo:nil  repeats:YES];

sharedManager.timerToggle = YES;
[self createPauseToolbar];

// //NSLog(@"Timer started");

}
else if (sharedManager.timerToggle == YES)
{
sharedManager.alertTimerActive = NO;
[timer invalidate];
                timer = nil;
// //NSLog(@"Timer Paused");
sharedManager.timerToggle = NO;
[self createPlayToolbar];
}

}

Calling the shared manager is the same anywhere you need it.   

If you have any questions i can certainly try to answer them. but  really read matts blog, it helped me alot.

Greg
Logged

Apps available on  iTunes store:
"ADACode"  iPhone and iPad versions, "ADAGuidelines" iPhone & iPad versions,  "Rehabilitation Act of 1973" for iPhone
"APokerTimer" now for iPhone http://bit.ly/h1fAJp
TotalLuck
Full Member
***
Posts: 107



WWW Email




Reply #4 on: April 27, 2012, 09:55:47 PM

Heyo! just thought i would post up the new way to handle this singleton under the ARC settings.  its actually much easier only one block to write now.

as you';; see it now uses the Grand Central Dispatch do do this.
Code: (Objective-C)
#import <Foundation/Foundation.h>

@interface SharedManager : NSObject
{
    NSMutableArray *testResultArray;
    NSMutableArray *currentTestArray;
    NSMutableArray *statArray;
    NSMutableArray *agTestQuestionArray;
    bool testInProgress;
     
}
@property (strong, nonatomic) NSMutableArray *testResultArray,*currentTestArray,*statArray,*agTestQuestionArray;
@property (nonatomic) bool testInProgress;

+ (id)sharedInstance;

@end

Code: (Objective-C)
#import "SharedManager.h"

@implementation SharedManager
@synthesize testResultArray,statArray,agTestQuestionArray,currentTestArray;
@synthesize testInProgress;

+ (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;
}

Thats all there is to it.  now reference it form any controller by using the  same callback:
Code: (Objective-C)
SharedManager *sharedManager = [SharedManager sharedInstance];
sharedManager.testInProgress = NO;

Also if you look in the Xcode snippet library you will find  the GCD code  for this. it looks like this
Code: (Objective-C)
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    <#code to be executed once#>
});

Have fun

Smiley Greg
Logged

Apps available on  iTunes store:
"ADACode"  iPhone and iPad versions, "ADAGuidelines" iPhone & iPad versions,  "Rehabilitation Act of 1973" for iPhone
"APokerTimer" now for iPhone http://bit.ly/h1fAJp
Pages: [1] Go Up
Print
Jump to:



Login with username, password and session length

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
Entire forum contents (c) 2009 classroomM.com. All rights reserved.