gpt4 book ai didi

ios - 单例类加载数据

转载 作者:行者123 更新时间:2023-11-29 11:13:30 25 4
gpt4 key购买 nike

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

我在想我的数据模型将不得不以某种方式委托(delegate)其他类?

最佳答案

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

关于ios - 单例类加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10495598/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com