1

我创建了一个单例类,它应该为我的应用程序处理所有数据加载,所有数据都是从 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 的那些类。

我在想我的数据模型必须以某种方式委托其他类?

4

2 回答 2

2

在这种情况下,您可以使用 NSNotificationCenter。

于 2012-05-08T09:08:50.497 回答
0

在 IOS 开发者库中,有一个名为 MVCNetworking 的示例项目,http://developer.apple.com/library/ios/#samplecode/MVCNetworking/Introduction/Intro.html

它的 NetworkManager 是一个单例类,将所有请求打包为 NSOperation,然后将其添加到 NSOperationQueue。

因此,甚至可以管理排队的网络请求,并以有限的并发数进行处理。

仅供参考,这行代码可能会导致内存泄漏:

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
于 2012-05-08T09:14:33.990 回答