开发者

problem with a singleton implementation

I've got a problem with a singleton implementation. It seems an objet I want to hold in my singleton gets corrupted and I can't figure why. Any help appreciated.

Here is the code of the singleton: SessionServices.h

    #import <Foundation/Foundation.h>

/**
 This class provides a simple way of getting information about the connected user
*/
@class  UserIHM;
@interface SessionServices : NSObject {
    @private
    UserIHM *user; //the object to retain
}

@property (nonatomic, retain) UserIHM *user;

sessionServices.m

@implementation SessionServices
@synthesize user;

static SessionServices *INSTANCE = nil;

+ (SessionServices*)sharedInstance
{
    if (INSTANCE == nil) {
        INSTANCE = [[super allocWithZone:NULL] init];
    }
    return INSTANCE;
}
....
//singleton impl from apple documentation
...
}

userIHM.h

@interface UserIHM : NSObject {
    @private
    NSString *tagUID;
    NSStrin开发者_如何学运维g *username;
    BOOL isAdmin;
}

@property (nonatomic,retain) NSString *tagUID;
@property (nonatomic,retain) NSString *username;
@property (nonatomic) BOOL isAdmin;

then in SessionServices.m I call:

user = [[IHMObjectFinderServices sharedInstance] getUserByTagUID:userTagUID];

and all the fields of the user get filled with correct info.

taguid = 2ac6912a username = Mike isAdmin = NO

then I try to use this info to set the title of my UITableView

self.navigationItem.title = [NSString stringWithFormat:@"Projects: %@",[[[SessionServices sharedInstance] user] username]];

if I NSLog and use the debugger, I can see that the username becomes an

invalid CFString

What am I doing wrong ?


This idiom is slightly better:

+(SessionServices *)singleton {
    static dispatch_once_t pred;
    static SessionServices *shared = nil;
    dispatch_once(&pred, ^{
        shared = [[SessionServices alloc] init];
        // init your variables here
        shared.blah = blahblah;
    });
    return shared;
}

See Care and Feeding of Singletons for an explanation.


As per your comment, the problem you are having depends on the fact that you don't initialize your *user ivar in the singleton implementation.

To do that, define a proper -init method. In this respect (initialization), singletons behave like normal classes.

- (id)init {
    self = [super init];
    if (self != nil) {
       user = [[UserIHM alloc] init];   //-- sergio: added alloc/init
       user.username = @"";
       user.tagUID = @"";
       user.isAdmin = NO;
    }
    return (self);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜