几周前我开始了 Objective-C 编程,所以我对所有这些部分如何组合在一起以及它们发生的顺序的理解仍然让我感到困惑。我正在尝试使用 NSURLSession 对我的一个应用程序进行 JSON API 调用。这一切都完美无缺,但我想用返回的一段数据更新标签,并且每当我查看/尝试更新标签时,我都会得到空值。
我发现的一些与我的问题相似的 SO 帖子包括:this、this、this和this。来自 Ruby on Rails 的世界,我根本不需要处理异步概念,但我知道我已经很接近了。
这是相关的代码片段:
if (!jsonError) {
NSDictionary *skillBuildData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"%@:", skillBuildNameLabel.text); // should say "Build Name" but returns null
NSLog(@"%@", skillBuildData[@"name"]); // correctly prints the result
NSLog(@"%@:", skillBuildNameLabel.text); // should have contents of skillBuildData[@"name"] but returns null
skillBuildNameLabel.text = skillBuildData[@"name"]; // obviously results in null, but I don't know why.
});
}
编辑:
不确定它是否相关,但我的大部分内容是ViewController.h
为了让您了解这个非常简单的应用程序中的出口和操作。一个按钮,一个方法,IBOutlet
链接按钮和 JSON 调用方法的,以及一个标签:
@interface ViewController : UIViewController {
IBOutlet UILabel *skillBuildNameLabel;
IBOutlet UIButton *getSkillBuildDataButton;
}
- (void)getSkillBuildDataById:(int) skillBuildId;
- (IBAction)buttonPressed;
好像我很接近,我只是看不到我缺少的链接。非常感谢您!
编辑2:
查看 Ben Kreeger 对我标记为答案的回复的评论。我没有将故事板中的实际标签连接到我在ViewController.h
. 我不知道您可以将线从情节提要中的元素拖到实际的代码行中。那是缺失的部分。看起来我还有很多关于 Xcode 和 Objective-C 的知识要学习。感谢所有帮助我的人!