Page 1 of 1

Share data by using class instanced Learn how you can use a class instance to share data Rate Topic: -----

#1 garfinkle  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 27
  • View blog
  • Posts: 87
  • Joined: 08-September 09

Posted 02 March 2010 - 03:30 PM

Hi All,

Here is a tutorial I just created on my iPhone Development Blog to show you how you can use an instance of a class to share data across multiple class files and instances. Think of it as a similar effect to using sessions in languages such as PHP or ASP.

The following system works by creating an instance of a class and passing the same instance to any class that requires use of the classes features. You can/probably will use this style for more advanced systems when you want only one instance. Good examples of this used on a larger scale is the Cocos2d system which uses a shared instance for handling the whole game framework.

So here goes:

The header file

The first file you will create will be the header file, for this example we are going to create temporary settings file for remembering details such as form variables (such as login names) or in game volume levels etc. (note this example is hypothetical and there are much better ways of saving settings information such as NSUserDefaults, this just makes for an easy to understand example)

Settings.h

 #import <Foundation/Foundation.h>

    @interface Settings  :  NSObject

    {

    //Declare some public variables that you may want to save

    NSString* username;

    NSString* email;

    float gameVolume;

    }

    //setup the properties for the variables above

    @property (nonatomic, retain) NSString* username;

    @property (nonatomic, retain) NSString* email;

    @property (nonatomic, retain) float gameVolume;

    // declare a couple of methods such as resetting the settings or saving the settings to a file

    -(void)  resetSettings;

    -(void) saveSettings:(NSString *)fileName;

    // declare the important method that will returned the shared instance

    // the + means that the method is a class method and is called when the class is called

    +(Settings *)sharedSettings;

    @end


The header file can contain as many variables or methods that you require, just remember that everything declared will be retained unless you manually remove it

Now on to the implementation file

The implementation file

Settings.m

 #import “Settings.h”      //include the header file

    // create the getters and setters for your public variables

    @synthesize username;

    @synthesize email;

    @synthesize gameVolume;

    static Setting*  _sharedSettings = nil; //declare a private variable to assign the instance to

    // Setup your class method to return the shared instance

    +(Settings *) sharedSettings

    {

    // create the instance using synchronized to lock the instance from being modified by anything other than where you are calling it from

    @synchronized([Settings class])

    {

    // if the instance does no exist yet, create it

    if(!_sharedSettings)

    [[self alloc] init];

    // return the instance;

    return _sharedSettings;

    }

    // do a return here so you do not get any compiler errors

    return nil;

    }

    // overide the default alloc method

    +(id) alloc

    {

    @synchronized([Settings class])

    {

    // if _sharedSettings isn’t = nil then for some reason the instance has tried to be created again

    // so throw an NSAssert error to let you know a serious issue has happened

    // A NSAssert  error is thrown if the check (_sharedSettings == nil) returns false

    NSAssert(_sharedSettings == nil, @”Attempted to allocate a second instance of the settings.”);

    _sharedSettings = [super alloc];

    return _sharedSettings;

    }

    // do a return here so you do not get any compiler errors

    return nil;

    }

    // now all the important stuff is done, just implement your public methods we declared in the header file

    -(void) resetSettings

    {

    username = @”";

    email = @”";

    gameVolume = 1.0f;

    }

    -(void) saveSettings:(NSString *)fileName

    {

    // write your code to save you settings to a file, plist or database etc.

    }

    @end


And that is it. Your shared instance is now setup and ready to be used.

Examples of how to use

When ever you want to use your shared instance, just include the header file in your code and called the method of variable directly by referencing the shared instance, nice and simple

  //example of use

    #include “Settings.h”

    //… other includes and the rest of your code

    // later in some method where you want to access your settings

    {

    //Retrieve the username by calling the username variable from the shared instance

    NSString* localUsername = [[Settings sharedSettings] username];

    //or maybe reassign the username

    [[Settings sharedSettings] setUsername:@”A User”];     //the setUsername method is created by the synthesize function

    //and then you might even save the settings

    [[Settings sharedSetting]  saveSettings:@”mySaveFile.plist”];

    }


So now you can see just how easy it is to access shared variables and methods, you do not even have to manually create an instance of the class or allocate it, it is done as soon as you access [[Settings sharedSettings] …. ]

Hope this little tutorial help.

Leave a comment if this helps you or if I have made a mistake. Also feel free to pop by my blog and drop me a little comment

Matt

Is This A Good Question/Topic? 0
  • +

Page 1 of 1