David Chelidze
David Chelidze

Reputation: 1204

Set variable to property class inside singleton Objective C

I have property User class and Singleton class named Auth. In the Auth class I am sending request to server and with result back I want to set User properties. Like setName, setLastname and so on. But I can't set User value and it always gives null.

Here is User.h

@interface User : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *lastname;
@end

Auth.h

#import "User.h"
@interface Auth : NSObject{
    User *user;
}

@property (nonatomic, retain) User *user;
@property (atomic, retain) NSString *token;

+(Auth *) getInstance;
-(void) doLogin:(void (^) (BOOL, NSDictionary *))comletion;
@end

Auth.m

#import "Auth.h"
#import "User.h"
#import "ServiceRequest.h"

@implementation Auth


@synthesize user;

+ (Auth *) getInstance
{   
    static Auth* sharedInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once( &predicate, ^{
        sharedInstance = [ [ self alloc ] init ];
    } );
    return sharedInstance;
}


-(void) doLogin:(void (^) (BOOL, NSDictionary * err))comletion{

    [[[ServiceRequest alloc] init] doLogin:^(NSDictionary *data, NSString *err) {

        if ([data objectForKey:@"errors"] != [NSNull null]) {
            comletion (NO, [data objectForKey:@"error"]);
         }else {

        [self.user setName:@"USER_NAME"];

           NSLog(@"USER NAME IN AUTH:%@",self.user.name);
            //RETURNS NULL:(

        }

    }];

}

Upvotes: 0

Views: 378

Answers (1)

developer
developer

Reputation: 76

//Checkpoint 1
if (self.user == nil) {
    self.user = [User new];
}
//Checkpoint2
[self.user setName:@"USER_NAME"];

Add checkpoint 1 before checkpoint 2 as self.user is not initialized, so use new keyword for this purpose.

Upvotes: 1

Related Questions