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