我创建了一个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:@"/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];
}
我一直在考虑实例变量,但是不确定执行此操作的最佳方法是什么。
最佳答案
尝试声明两个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和密码传递nil,然后在其他方法中检查nil并提供一些默认值。
另一个可能的选择是,由于init调用似乎不需要用户ID和密码,因此只需将它们声明为属性并手动设置即可
[yourClass sharedClient].userID = @"id";
[yourClass sharedClient].password = @"password";