【发布时间】:2014-01-20 03:36:09
【问题描述】:
我正在尝试将 SVProgressHUD 与 cocoapods 一起使用。我已经按照大量在线教程将它安装在我的 xcode 工作区中。使用起来似乎很简单,但我无法让它工作。这是我从 rottentomatoes 应用程序加载数据的代码。我想在网络请求执行其操作时显示“加载”。我想知道这是否是ui线程问题?我在网络请求中添加了睡眠,因为结果返回得太快了!
- (void) reload{
[SVProgressHUD showWithStatus:@"Updating" maskType:SVProgressHUDMaskTypeBlack];
NSString *url = @"http://api.rottentomatoes.com/api/public/v1.0/lists/dvds/top_rentals.json?";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
[NSThread sleepForTimeInterval:3];
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[object objectForKey:@"movies"]];
self.movies = [[NSMutableArray alloc]init];
for(NSDictionary *item in array){
SFMovie *movie = [[SFMovie alloc]initWithDictionary:item];
[self.movies addObject:movie];
}
[SVProgressHUD dismiss];
[self.tableView reloadData];
}];
}
编辑评论: 两个 init 方法都调用了重新加载(因为我在这个项目中使用了故事板)
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
[self reload];
}
return self;
}
- (id) initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if(self){
[self reload];
}
return self;
}
第二次编辑: 我添加了一个下拉刷新,当我拉下 tableview 时会出现“更新...”。但它没有出现在init上。
- (void)viewDidLoad
{
[super viewDidLoad];
UIRefreshControl *refreshControl = [UIRefreshControl new];
[refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to refresh..."];
self.refreshControl = refreshControl;
}
- (void)refresh:(UIRefreshControl *)sender{
[self reload];
[sender endRefreshing];
}
所以我想我不能在 init 方法上运行 UI 的东西,因为视图还没有准备好。我现在在 viewdidload 上调用 reload 方法,它可以工作文件。谢谢约翰!
【问题讨论】:
-
主线程上是否调用了
reload? -
@John reload 是从 init 方法调用的,所以我猜它是 UI 线程。谢谢。
-
这并不完全与答案有关,但我建议将该逻辑移至
viewDidLoad- 因为此时tableView尚未完全准备好,使用@987654327 发送请求回调中的 @ 引入了竞争条件。 -
谢谢@John。我添加了第二个编辑并做了您在此处提到的相同操作。这似乎解决了我的问题。
-
太好了,我会为以后的观点回答问题