1

I'm new in iOS programming and I am very interested in what singleton class is, and why it is used. I found some information but it is vague. In particular I would like to apply it to real example. My project use Facebook SDK and I want to create singleton class for my NSDictionary which contain friends list. My .m delegate file:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//here is some other code

facebook = [[Facebook alloc] initWithAppId:@"my app id" andDelegate:self];

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"FBAccessTokenKey"] 
    && [defaults objectForKey:@"FBExpirationDateKey"]) {
    facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
    facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
}

if (![facebook isSessionValid]) {
    NSArray *permissions = [[NSArray alloc] initWithObjects:
                            @"user_location", 
                            @"friends_location",
                            @"read_friendlists",
                            nil];
    [facebook authorize:permissions];
    [permissions release];
}
[facebook requestWithGraphPath:@"me/friends" andDelegate:(id)self];

//here is some other code
}

And I set to my NSDictionary value of request which return friends list:

- (void)request:(FBRequest *)request didLoad:(id)result {
_friendsDictionary = result;
}

In which way I need to write singleton class and do not use delegate class AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];.

RomanHouse
  • 2,552
  • 3
  • 23
  • 44

3 Answers3

6

singletons are a class that only gets instantiated once in your application’s run-time. They often take the form of manager or factory classes .. they used when you want to keep the object always live in the memory , usually I used for global class which contain global functions and variables that I need in many places on my app.

The simplest example to implement singleton pattern is like this

in .h

#import <Foundation/Foundation.h>

@interface MySingleton : NSObject {

}
+(MySingleton*)sharedMySingleton;
-(void)sayHello;
@end

in .m

@implementation MySingleton
static MySingleton* _sharedMySingleton = nil;

+(MySingleton*)sharedMySingleton
{
    @synchronized([MySingleton class])
    {
        if (!_sharedMySingleton)
            [[self alloc] init];

        return _sharedMySingleton;
    }

    return nil;
}


-(void)sayHello {
    NSLog(@"Hello World!");
}
@end

So in any class in your project to fire tha say hello function you just need to import this class and then call the function like this [MySingleton sharedMySingleton] sayHello];

Hope this will be helpful.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Malek_Jundi
  • 6,140
  • 2
  • 27
  • 36
  • 1
    You can also add the properties like "FacebookID , UserInfo , etc.." and build get/set method to many purpose in your application ! – Sakares May 02 '12 at 08:18
  • So I need to write the same methods in my singleton class as in delegate? – RomanHouse May 02 '12 at 08:39
  • as @Jojas said .. you can define any property you want as the facebook instance and access it at any class in your project through your singleton class .. also you can implement the Facebook delegate method in the singleton class as you do in the normal classes. – Malek_Jundi May 02 '12 at 08:46
  • @Malek_Jundi but if I implement Facebook delegate method and next will be use it, won't it be the same as I will be use just delegate method? – RomanHouse May 02 '12 at 09:05
  • No you will move the implement from the app delegate to your singleton class .. so you will not use the app delegate any more. – Malek_Jundi May 02 '12 at 09:12
3

Have a read of these: Singletons, more singletons, SO Post, Singleton in Obj-c. Google throws up maybe 10 decent results on the first page.

btw, you may not be retaining result as im assuming _friendsDictionary is an ivar and not a property.

Community
  • 1
  • 1
Martin
  • 747
  • 6
  • 11
2

The Singleton pattern should NOT be used in iOS code. A singleton is a memory leak, by definition. What you should be doing instead is creating a single instance that is referenced from the app delegate. You can create just one instance, like a singleton, but just make sure you do not create a static (private) variable that is never released. A ref from the app delegate can always be set to nil to determine if memory is getting released. You can't do that with the singleton approach described above.

Take care to only ref data from this instance, since references to UIView derived elements will leak a lot of system memory because they are not cleaned up.

MoDJ
  • 4,309
  • 2
  • 30
  • 65