单例类加载数据

时间:2012-05-08 09:01:19

标签: ios delegates singleton loader

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

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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];