将变量设置为singleton Objective C中的属性类

时间:2016-03-25 11:25:33

标签: objective-c properties singleton

我有属性User类和Singleton类名为Auth。在Auth类中,我向服务器发送请求,结果返回我想设置用户属性。像setName,setLastname等。但我无法设置用户值,它始终为空。

这是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:(

        }

    }];

}

1 个答案:

答案 0 :(得分:1)

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

在检查点2之前添加检查点1,因为self.user未初始化,因此为此目的使用new关键字。