457Singleton Classes and Shared Resources in Objective-C

Resource.h

#import 

@interface Resource : NSObject {
    float myValue;
}

@property float scale;

+ (id)shared;

@end

 

Resource.m

#import "Resource.h"

@implementation Resource

@synthesize scale;

- (id)init {
    scale = 1.0f    // my default value
}

+ (id)shared {
    static Resource *sharedResource = nil;
    if (!sharedResource) {
        sharedResource = [[self alloc] init];
    }
    return sharedResource;
}
@end

An now it can be used like the following:

Resource *r = [Resource shared];
NSLog(@"Resource Test: %f", [r myValue]);
// Resource Test: 1.000000

[r setMyValue:2.0];
NSLog(@"Resource Test: %f", [r myValue]);
//# Resource Test: 2.000000

Resource *s = [Resource shared];
[s setMyValue:2.111];
NSLog(@"Resource Test: %f", [s myValue]);
// Resource Test: 2.111000

NSLog(@"Resource Test: %f", [r myValue]);
//Resource Test: 2.111000

Note that the values stays constant, even if another instantionation occurs. I guess that's what Singleton classes are all about.

Adapted from Scott Stevenson's fantastic introduction at Cocoa Dev Central.

And more tutorials from Scott Stevenson... Cocoa Dev Central: Learn C for Cocoa Cocoa Dev Central: Learn Objective C