我创建了一个单例类,它应该为我的应用程序处理所有数据加载,所有数据都是从 Web 界面加载的,但在不同的请求中。
DataModel *instance = [[[DataModel instance] init] autorelease];
[instance doRequestFromLocation:@"users" withPostType:@"GET" andData:@"data"];
[instance doRequestFromLocation:@"timezones" withPostType:@"GET" andData:@"data"];
例如,这将在一个请求中加载所有用户,然后在另一个请求中加载所有时区。
我的单例类如下所示:
// Send a curl request
- (void)doRequestFromLocation:(NSString *)location withPostType:(NSString *)type andData:(NSString *)data
{
// NSArray *keys = [NSArray arrayWithObjects:@"username", @"password", nil];
// NSArray *objects = [NSArray arrayWithObjects:@"test", @"test", nil];
// NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObject:objects forKey:keys];
NSString *username = @"username";
NSString *password = @"password";
NSString *urlString = [url stringByAppendingFormat:@"%@", location];
NSMutableString *loginString = (NSMutableString *)[@"" stringByAppendingFormat:@"%@:%@", username, password];
NSLog(@"%@", loginString);
NSString *encodedLoginData = [Base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]];
NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@",encodedLoginData];
NSLog(@"%@", authHeader);
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:type];
[theRequest setValue:authHeader forHTTPHeaderField:@"Authorization"];
[theRequest setValue:@"application/xml" forHTTPHeaderField:@"Content-type"];
[theRequest setValue:@"application/xml" forHTTPHeaderField:@"Accept"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
}
#pragma mark -
#pragma mark Responses
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", responseString);
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connectionDidFinishLoading");
}
虽然这一切都很好,但我的下一步有点卡住了。
我希望能够从任何地方调用 doRequestFromLocation(现在可以),但我希望其他类能够响应它进入 didReceiveData 的那些类。
我在想我的数据模型必须以某种方式委托其他类?