在我的一个视图控制器中,我根据从单独的NSObject
类接收到的“GET”数据设置标签。显然,设置标签所需的时间比获取数据所需的时间要少得多,因此标签始终设置为 nil。如何确保在数据获取完成之前不会设置标签。
NSObject
这是在类中执行“获取”的方法myClass
- (void) doGetURL:(NSString *) urlstring
callBackTarget:(id) target
callBackMethod:(NSString *) method
failedMethod:(NSString *) method_failed
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlstring]];
NSLog(@"-- get URL with cookie : [%@] and hash:(%@)", [self cookie], [self modhash]);
if (cookie && [cookie length] > 0)
{
NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
cookieDomain, NSHTTPCookieDomain,
@"/", NSHTTPCookiePath,
@"reddit_session", NSHTTPCookieName,
cookie, NSHTTPCookieValue,
// [cookie stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], NSHTTPCookieValue,
nil];
NSHTTPCookie *http_cookie = [NSHTTPCookie cookieWithProperties:properties];
NSArray* cookies = [NSArray arrayWithObjects: http_cookie, nil];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
[request setAllHTTPHeaderFields:headers];
}
NSURLConnection * connection = [NSURLConnection connectionWithRequest:request delegate:self];
NSString *connectionKey = [NSString stringWithFormat: @"%ld", ((intptr_t) connection)];
NSMutableDictionary *dl = [[NSMutableDictionary alloc] init];
[dl setValue:connectionKey forKey:@"connectionKey"];
if (target && method)
{
[dl setValue:target forKey:@"afterCompleteTarget"];
[dl setValue:method forKey:@"afterCompleteAction"];
}
[dl setValue:method_failed forKey:@"failedNotifyAction"];
[connections setValue:dl forKey:connectionKey];
}
这是在另一个方法中调用的myClass
- (void)getUserInfo:(NSString*)user
{
NSString *getString = [NSString stringWithFormat:@"%@/user/%@/about.json",server,user];
[self doGetURL:getString callBackTarget:self callBackMethod:@"userInfoResponse:" failedMethod:@"connectionFailedDialog:"];
}
回调方法:
- (void)userInfoResponse:(id)sender
{
NSLog(@"userInfoResponse in()");
NSData * data = (NSData *) sender;
NSError *error;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSDictionary *response = [json objectForKey:@"data"];
//futureLabelStr is a property of myClass
futureLabelStr = [response objectForKey:@"name"];;
}
然后在 View Controller 中设置标签:
- (void)viewDidLoad
{
[myClass getUserInfo:@"some_user"];
myLabel.txt = myClass.futureLabelStr;
}
请让我知道我需要添加更多或任何我试图尽我所能组织它的东西,但我可能错过了一些东西。