我以前从未接触过线程,从它的外观来看,我可能需要深入研究一下它们,但我想知道是否有一个更简单的解决方案来解决下面的问题。
我基本上是在 UITableView
中显示用户的 Facebook 好友列表。 。我有一个FacebookWrapper
包含我所有 Facebook 方法的类,以及 FacebookViewController
有各种按钮/选项。最后还有一个FriendsViewController
显示好友列表。用户可以通过按FacebookViewController
中的相关按钮来选择显示男性好友或女性好友列表。 。
[facebook requestWithMethodName:@"fql.query" andParams:dictionary andHttpMethod:@"GET" andDelegate:self];
包装类中的委托(delegate)方法处理 FBRequest
被返回。我有以下方法来确定此时发生的情况:
- (void)requestLoading:(FBRequest *)request {
NSLog(@"Loading...");
}
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
NSLog(@"Response received");
}
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(@"Request failed");
}
- (void)request:(FBRequest *)request didLoadRawResponse:(NSData *)data {
NSLog(@"Request did load raw response");
}
但是,例如,当我点击“男性 friend ”按钮时,我想等到生成响应后再按 FriendsViewController
并显示列表。就目前情况而言,FriendsVC 在请求返回列表之前被推送,因此我得到一个空白列表。在刷新表格并显示结果之前,我必须等待“请求确实加载原始响应”。目前调用并显示好友列表的方法在 FacebookViewController
看起来像这样:
- (IBAction)friendsButtonPressed:(id)sender {
int selectionTag = [sender tag];
//Get access to the instance of the wrapper in the app delegate (since it needs to remain refereced after app exits to log in and returns
MiniBfAppDelegate *appDelegate = (MiniBfAppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.facebookWrapper loadListDataFor:selectionTag];
//Initialise the friends view controller
FriendsViewController *friendsViewController = [[FriendsViewController alloc] init];
//NEED TO WAIT UNTIL LISTDATA IS RETURNED?
//Give the friends view controller the list data
friendsViewController.listData = appDelegate.facebookWrapper.friendsList;
//Push the friends view controller
friendsViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self.navigationController pushViewController:friendsViewController animated:YES];
[friendsViewController release];
}
所以理想情况下,我想在等待包装器返回列表时显示一个加载符号,一旦返回,就推送 FriendsViewController 以便立即填充它。那么我需要使用线程还是有更简单的方法?
也许这正在回答我自己的问题,并且可能是我在这里未能掌握一个基本概念,但是除了在我的应用程序委托(delegate)中创建 FriendsVC 的实例之外,还有什么方法可以发送当前的实例来自 Wrapper 类的消息?所以我可以直接告诉它 refresh
在包装的 request: didLoadRawResponse:
方法,即当生成列表时。
最佳答案
我不确定我是否理解您的问题,但您可能想查看 NSNotificationCenter。您可以使用它向 Controller 发送消息,下面是触发通知的示例:
[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotificationName"
object:self
userInfo:[NSDictionary dictionaryWithObject:XXXX forKey:@"someObject"]];
如您所见,您甚至可以向其发送参数。在目标 Controller 中,您只需注册一个观察者来响应这些消息:
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(yourMethodHere:)
name: @"myNotificationName"
object: nil];
问候!
关于objective-c - 使用线程等待另一个类的方法执行,或者有更简单的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8912498/