gpt4 book ai didi

ios - Objective-C 中的 SIGBRT 错误,可能来自尝试的 JSON 请求

转载 作者:行者123 更新时间:2023-11-29 01:45:46 27 4
gpt4 key购买 nike

我在 Objective-C 中处理简单的 JSON 请求时遇到了问题。当我尝试执行代码时,它给了我这个错误:

2015-08-11 12:11:15.552 WordADay[11482:1877243] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x7fa4d8e87270> valueForUndefinedKey:]: this class is not key value coding-compliant for the key text.'
*** First throw call stack:
(
0 CoreFoundation 0x000000010c01bc65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010bcb4bb7 objc_exception_throw + 45
2 CoreFoundation 0x000000010c01b8a9 -[NSException raise] + 9
3 Foundation 0x000000010b8da82a -[NSObject(NSKeyValueCoding) valueForUndefinedKey:] + 226
4 Foundation 0x000000010b833b23 -[NSObject(NSKeyValueCoding) valueForKey:] + 251
5 WordADay 0x000000010b7823f2 -[ViewController getNewWord] + 1442
6 WordADay 0x000000010b781e09 -[ViewController viewDidLoad] + 73
7 UIKit 0x000000010c5451d0 -[UIViewController loadViewIfRequired] + 738
8 UIKit 0x000000010c5453ce -[UIViewController view] + 27
9 UIKit 0x000000010c460289 -[UIWindow addRootViewControllerViewIfPossible] + 58
10 UIKit 0x000000010c46064f -[UIWindow _setHidden:forced:] + 247
11 UIKit 0x000000010c46cde1 -[UIWindow makeKeyAndVisible] + 42
12 UIKit 0x000000010c410417 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 2732
13 UIKit 0x000000010c41319e -[UIApplication _runWithMainScene:transitionContext:completion:] + 1349
14 UIKit 0x000000010c412095 -[UIApplication workspaceDidEndTransaction:] + 179
15 FrontBoardServices 0x000000010ebd55e5 __31-[FBSSerialQueue performAsync:]_block_invoke_2 + 21
16 CoreFoundation 0x000000010bf4f41c __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
17 CoreFoundation 0x000000010bf45165 __CFRunLoopDoBlocks + 341
18 CoreFoundation 0x000000010bf44f25 __CFRunLoopRun + 2389
19 CoreFoundation 0x000000010bf44366 CFRunLoopRunSpecific + 470
20 UIKit 0x000000010c411b02 -[UIApplication _run] + 413
21 UIKit 0x000000010c4148c0 UIApplicationMain + 1282
22 WordADay 0x000000010b782aaf main + 111
23 libdyld.dylib 0x000000010e5bf145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

当我不尝试执行这个奇怪的 JSON 请求时,它执行得很好......但是当我这样做时,它会抛出该错误。我想知道我应该做什么...这是 JSON 请求背后的代码:

//
// ViewController.m
// WordADay
//
// Created by Lucas Steuber on 8/11/15.
// Copyright (c) 2015 Lucas Steuber. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *word;
@property (weak, nonatomic) IBOutlet UILabel *definition;

@end

@implementation ViewController
- (IBAction)newWord:(id)sender {
[self getNewWord];
}

- (IBAction)moreInfo:(id)sender {

}

- (void)viewDidLoad {
[super viewDidLoad];
[self getNewWord];
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (void)getNewWord {
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"dictionary" ofType:@"txt"];
NSString *fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

NSArray *values = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];


NSUInteger randomIndex = arc4random() % [values count];
NSString *word = values[randomIndex];

NSString *urlp1 = @"http://api.wordnik.com:80/v4/word.json/";
NSString *urlp2 = @"/definitions?limit=1&includeRelated=true&sourceDictionaries=wiktionary&useCanonical=false&includeTags=false&api_key=a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5";
NSURL *wordnik = [NSURL URLWithString: [NSString stringWithFormat: @"%@%@%@", urlp1, word, urlp2]];

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:wordnik
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
NSError *jsonArrayError;
NSString *desc;

// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];

NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: urlData options: NSJSONReadingMutableContainers error: &jsonArrayError];

if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", jsonArrayError);
} else {
NSArray *items = [jsonArray objectAtIndex:0];
for (NSDictionary *item in items){
desc = [item valueForKey:@"text"];
}
}


self.word.text = word;
self.definition.text = desc;
}
@end

我对 Objective-C 还很陌生,到目前为止我还不太喜欢它。

编辑:这是我正在解析的 JSON:

[{"textProns":[],"sourceDictionary":"wiktionary","exampleUses":[],"relatedWords":[],"labels":[],"citations":[],"word":"hello","partOfSpeech":"interjection","attributionText":"from Wiktionary, Creative Commons Attribution/Share-Alike License","attributionUrl":"http://creativecommons.org/licenses/by-sa/3.0/","text":"A greeting (salutation) said when meeting someone or acknowledging someone’s arrival or presence.","score":0.0}]

最佳答案

您的 JSON 是一个包含一个字典的数组。但是您的代码采用了不同的结构。以下应符合实际数据格式:

NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: urlData options: NSJSONReadingMutableContainers error: &jsonArrayError];

if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", jsonArrayError);
} else {
for (NSDictionary *item in jsonArray){
desc = item[@"text"];
}
}

但是遍历一个字典是没有意义的,所以它可以简化为:

NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: urlData options: NSJSONReadingMutableContainers error: &jsonArrayError];

if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", jsonArrayError);
} else {
NSDictionary *item = [jsonArray firstObject];
desc = item[@"text"];
}

另请注意,您不应使用 valueForKey:NSDictionary 中获取值。使用 objectForKey: 或现代语法(就像我在此处的代码中所做的那样)。

关于ios - Objective-C 中的 SIGBRT 错误,可能来自尝试的 JSON 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31950141/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com