我正在尝试运行此代码,但它无法运行。我已经尝试过列出同样问题的其他解决方案,但到目前为止还没有工作。我尝试将一个nslog放在dispatch_async中,但它甚至没有被调用。
- (void)viewDidLoad {
[super viewDidLoad];
self.keyboard = [[[NSBundle mainBundle] loadNibNamed:@"Keyboard" owner:nil options:nil] objectAtIndex:0];
[self addGesturesToKeyboard];
self.inputView = self.keyboard;
}
- (void)addGesturesToKeyboard {
[self.keyboard.searchKey addTarget:self action:@selector(pressSearchKey) forControlEvents:UIControlEventTouchUpInside];
}
- (void)pressSearchKey {
NSInteger numberOfResults = 3;
NSString *searchString = self.keyboard.textField.text;
NSString *encodedSearchString = [searchString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *finalSearchString = [NSString stringWithFormat:@"https://itunes.apple.com/lookup?term=%@&entity=song&limit=%ld",searchString,numberOfResults];
NSURL *searchURL = [NSURL URLWithString:finalSearchString];
dispatch_queue_t iTunesQueryQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, kNilOptions);
dispatch_async(iTunesQueryQueue, ^{
self.keyboard.firstLabel.text = @"hi";
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:searchURL];
if (data && !error) {
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.results = [NSMutableArray array];
NSArray *resultsArray = [JSON objectForKey:@"results"];
for (NSDictionary *bpDictionary in resultsArray) {
// self.keyboard.firstLabel.text = [bpDictionary objectForKey:@"trackName"];
}
}
});
[self.keyboard.view1 setHidden:YES];
[self.keyboard.view2 setHidden:NO];
}
已更新
dispatch_async(iTunesQueryQueue, ^{
NSError *error = nil;
NSData *data = [[NSData alloc] initWithContentsOfURL:searchURL options:NSDataReadingUncached error:&error];
if (data && !error) {
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSArray *array = [JSON objectForKey:@"results"];
dispatch_async(dispatch_get_main_queue(), ^{
self.keyboard.firstLabel.text = [array objectAtIndex:0];
});
}
});
答案 0 :(得分:0)
除了向队列添加块之外,还需要让系统服务队列。这可以通过在dispatch_main()
初始化结束时调用NSApplicationMain()
,UIApplicationMain()
,main()
或类似内容来完成。
示例:
#include <dispatch/dispatch.h>
#include <stdio.h>
int main() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
printf("Example\n");
});
dispatch_main();
}
此外,为什么要将kNilOptions传递给dispatch_get_global_queue?请传递0。