Search code examples
iosdelegatessingletonloader

singleton class loading data


I've created a singleton class that should handle all the data loading for my application, all data is loaded from a web interface, but in different requests.

DataModel *instance = [[[DataModel instance] init] autorelease];
[instance doRequestFromLocation:@"users" withPostType:@"GET" andData:@"data"];
[instance doRequestFromLocation:@"timezones" withPostType:@"GET" andData:@"data"];

This will for instance load all the users in one request and then load all the timezones in another.

My singleton class looks like this:

// 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");
}

While this all works fine, I'm a little stuck on my next step.

I want to be able to call doRequestFromLocation from everywhere (which is possible now), but I want other classes to respond to it ones it enters the didReceiveData.

I'm thinking my data model will somehow have to delegate the other classes?


Solution

  • In this case, you can use NSNotificationCenter.