Objective C - sample Singleton implementation

前端 未结 6 973
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 07:37

*I definitely need a break... cause was simple - array was not allocated... Thanks for help. Because of that embarrassing mistake, I flagged my post in order to delete i

相关标签:
6条回答
  • 2020-12-20 08:22

    in this function +(PeopleDatabase *)getInstance i think you need to place curly Braces correctly : like this

    +(PeopleDatabase *)getInstance {
        @synchronized(self)
        {
            if (instance == nil)
            {
                NSLog(@"initializing");
                instance = [[[self alloc] init] retain];
                NSLog(@"Address: %p", instance);
            }
            return instance ;
        }
    }
    
    0 讨论(0)
  • 2020-12-20 08:27

    This is an error that can be avoided by some disziplined convention which is to always use curly brackets followed by if and else.

    +(PeopleDatabase *)getInstance {
        @synchronized(self)
        {
            if (instance == nil)
                NSLog(@"initializing");
                instance = [[[self alloc] init] retain];
                NSLog(@"Address: %p", instance);
        }
        return(instance);
    }
    

    If instance is nil then the very next statement and only that is executed. And that is the nslog and not the allocation. Then instance is allocated anyway, regardless wether it was used before or not. This will provide you with a new singleton on each call. BTW that causes a leak.

    +(PeopleDatabase *)getInstance {
        @synchronized(self)
        {
            if (instance == nil) {
                NSLog(@"initializing");
                instance = [[[self alloc] init] retain];
                NSLog(@"Address: %p", instance);
            }
        }
        return(instance);
    }
    

    But this error came in while debugging. It may confuse you but does not solve your original problem. Please add an alloc and init and retain for _arrayOfPeople as well.

    -(id)init{
        if(self = [super init]) {
            Person* person = [[[Person alloc] initWithName:@"John" sname:@"Derovsky" descr:@"Some kind of description" iconName:@"johnphoto.png" title:Prof] retain];
    
            _arrayOfPeople = [[[NSMutableArray alloc] init] retain]; //dont forget the release
            [_arrayOfPeople addObject:person];
            NSLog(@"array count = %d", [_arrayOfPeople count]); // <== array count = 1 !!!  
            [person release];
        }
        return self;
    }
    

    In your code _arrayOfPeople is nil and addObject is sent to nil which does not cause an abort but does not do anything either. Then count is sent to nil wich returns 0/nil.

    0 讨论(0)
  • 2020-12-20 08:32
        @synchronized(self)
        {
            if (instance == nil)
                NSLog(@"initializing");
                instance = [[[self alloc] init] retain];
                NSLog(@"Address: %p", instance);
        }
    

    You appear to be missing your braces for that if statement. As written, the only thing you do different when instance == nil is emit a log message.

    0 讨论(0)
  • 2020-12-20 08:33

    The standard way of creating a singleton is like...

    Singleton.h

    @interface MySingleton : NSObject
    
    + (MySingleton*)sharedInstance;
    
    @end
    

    Singleton.m

    #import "MySingleton.h"
    
    @implementation MySingleton
    
    #pragma mark - singleton method
    
    + (MySingleton*)sharedInstance
    {
        static dispatch_once_t predicate = 0;
        __strong static id sharedObject = nil;
        //static id sharedObject = nil;  //if you're not using ARC
        dispatch_once(&predicate, ^{
            sharedObject = [[self alloc] init];
            //sharedObject = [[[self alloc] init] retain]; // if you're not using ARC
        });
        return sharedObject;
    }
    
    @end
    
    0 讨论(0)
  • 2020-12-20 08:33

    Check this apple doc on how to create singleton instance:

    https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html

    0 讨论(0)
  • 2020-12-20 08:38

    After web reading and personal practicing, my current singleton implementation is:

    @interface MySingleton
    
    @property myProperty;
    +(instancetype) sharedInstance;
    
    @end
    
    
    @implementation MySingleton
    
    + (instancetype) sharedInstance
    {
        static dispatch_once_t pred= 0;
        __strong static MySingleton *singletonObj = nil;
        dispatch_once (&pred, ^{
            singletonObj = [[super allocWithZone:NULL]init];
            singletonObj.myProperty = initialize ;
        });
    
        return singletonObj;
    }
    
    +(id) allocWithZone:(NSZone *)zone
    {
        return [self sharedInstance];
    }
    
    -(id)copyWithZone:(NSZone *)zone
    {
        return self;
    }
    

    this is a thread safe implementation and avoids the risk to create new objects by calling "alloc init" on your class. Attributes initialization has to occur inside the block, not inside "init" override for similar reasons.

    0 讨论(0)
提交回复
热议问题