2014-06-29 27 views
1

我创建了一个sharedClient传递值到sharedClient

+ (id)sharedClient { 
static MyClient *__instance; 
static dispatch_once_t onceToken; 
dispatch_once(&onceToken, ^{ 
    NSURLComponents *urlComponents = [NSURLComponents componentsWithString:BASE_URL]; 
    urlComponents.user = @"username"; 
    urlComponents.password = @"password"; 
    NSURL *url = urlComponents.URL; 
    NSLog(@"%@",url); 
    __instance = [[MyClient alloc] initWithBaseURL:url]; 
}); 
    return __instance; 
} 

但正如你可以看到我已经硬编码的用户名和密码。将变量传递到此类和sharedClient的最佳方式是什么?目前我打电话,像这样

- (IBAction)login:(id)sender { 
[SVProgressHUD show]; 

[[MyClient sharedClient]getPath:@"https://stackoverflow.com/users/current.json" 
          parameters:nil 
           success:^(AFHTTPRequestOperation *operation, id responseObject) { 

            NSString *authToken = [responseObject valueForKeyPath:@"user.api_key"]; 
            [self.credentialStore setAuthToken:authToken]; 

            [SVProgressHUD dismiss]; 

            [self performSegueWithIdentifier: @"loginSuccess" sender: self]; 

           } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
            if (operation.response.statusCode == 500) { 
             [SVProgressHUD showErrorWithStatus:@"Something went wrong!"]; 
            } else { 
             NSData *jsonData = [operation.responseString dataUsingEncoding:NSUTF8StringEncoding]; 
             NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData 
                          options:0 
                          error:nil]; 
             NSString *errorMessage = [json objectForKey:@"error"]; 
             [SVProgressHUD showErrorWithStatus:errorMessage]; 
            } 
           }]; 


    [SVProgressHUD dismiss]; 
} 

我一直在思考的实例变量,但不确定什么是最好的方式做,这将是客户端。

回答

2

尝试声明两个sharedClient方法,其中一个使用另一个但提供更多信息。例如

+ (id)sharedClient { 
    return [self sharedClientWithUserID:@"default user" andPassword:@"default password"]; 
} 

+ (id)sharedClientWithUserID:(NSString *)userID andPassword:(NSString *)password { 
    //move your dispatch once code here and use the provided userID and password 
} 

你也可以有sharedClient通零的用户ID和密码,然后零通过另一种方法检查中,并提供一些默认值。

另一种可能的选择,因为你似乎没有需要用户ID和密码为init调用的是刚刚宣布他们的属性和手动设置

[yourClass sharedClient].userID = @"id"; 
[yourClass sharedClient].password = @"password";