【问题标题】:How To Check key in key pair is available or not?如何检查密钥对中的密钥是否可用?
【发布时间】:2018-06-09 18:03:07
【问题描述】:

我正在尝试使用 iOS 学习 json。 我正在尝试使用UITableView 实现json 数据。在我的表格视图行中,标题和副标题正在显示这些值。我可以在标题中加载数据,但是当尝试在字幕中加载时,应用程序崩溃了,因为在 subtitle result 中给出了 json 的该字段和许多键对值。所以无法在tableview的副标题中显示。

我的问题是如何加载字幕,以及当单击它时是否可以使用许多键对值中的键,它会被重定向到其他 tableview 以显示该数据。

我的代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://query.yahooapis.com/v1/public/yql?q=select+*+from+weather.forecast+where+woeid%3D1100661&format=json"]];
    NSError *error=nil;
    id response=[NSJSONSerialization JSONObjectWithData:data options:
                 NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error]; 
    if (error) {
        NSLog(@"%@",[error localizedDescription]);
    } else {
        _query = [response objectForKey:@"query"];
        NSLog(@"%@",_query);
        _keyArray = [_query allKeys];   
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_keyArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *cellIdentifier = @"cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] ;
    }

    NSString *key = [_keyArray objectAtIndex:indexPath.row];
    //NSString *dictionary = [_query objectForKey:key];
    NSString *dictionary = [_query objectForKey:key];
    cell.textLabel.text = key;
    cell.detailTextLabel.text = dictionary;  
    return cell; 
}

谢谢。

【问题讨论】:

  • 取决于 .. 你想在 cell.detailTextLabel 中显示什么?
  • 我非常努力地理解你真正想要在这里得到的输出,但我不能。请添加一张图片,其中提到了您真正想要的结果。
  • 如果subtitle的值是新的字典,是扩展tableview还是push到新的tableview显示子键值对。
  • @ArunKumar 我会在键值中显示 cell.detailTextLabel。但结果是许多密钥对可用,因此应用程序将崩溃。
  • 您可以在设置为detailTextlabel之前检查字典的类型。 cell.detailTextLabel.text = [字典 isKindOfClass:[NSString 类]] ?字典:“变量不是字符串”

标签: ios objective-c json uitableview nsdictionary


【解决方案1】:

我从你的问题和cmets中了解到的事情,这是我一步一步的回答......

首先,我在我的ViewController.h 类中采用了NSArrayNSDictionary 属性,就像这样。

{
NSArray *_allKeys;
}
 @property(nonatomic,strong) NSDictionary *query;

然后在ViewController.m 中,我为query 属性创建了一个setter 方法,我将数据设置为_query_allKeys,就像这样...

 -(void)setQuery:(NSDictionary *)query
{
    _query = query;
    _allKeys = [_query allKeys];
    if ([self isViewLoaded]) {
        [tableView reloadData];
    }

}

现在在 UITableView 数据源方法 cellForRow 中,我已经更新了你的代码..

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    NSString *key = _allKeys[indexPath.row];
    id value = _query[key];
    cell.textLabel.text = key;
    if ([value isKindOfClass: [NSString class]]) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.detailTextLabel.text = (NSString*)value;
    }
    else if ([value isKindOfClass: [NSDictionary class]])
    {
        cell.detailTextLabel.text = @"More Info";
         cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    else if ([value isKindOfClass: [NSArray class]])


       {
            cell.detailTextLabel.text = @"Multiple Entries Found";
             cell.accessoryType = UITableViewCellAccessoryNone;

// do something show array data with prototype custom cell
        }
        return cell;
    }

现在在UITableView 委托方法didSelect 中,我为相同的ViewController 创建了一个新实例(我们可以重用它,因为它具有相同的UI 布局),并传递_query 的值。 .

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *key = _allKeys[indexPath.row];
    id value = _query[key];
    if ([value isKindOfClass: [NSDictionary class]])
    {
        ViewController *nextVC = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewController"];
        nextVC.query = value;
        [self.navigationController pushViewController:nextVC animated:YES];
    }
}

注意:每当我实例化 ViewController 实例时,我不想在 ViewController.m 中调用 webservice 。所以我把webservice代码放在AppDelegatedidFinishLaunch方法中。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://query.yahooapis.com/v1/public/yql?q=select+*+from+weather.forecast+where+woeid%3D1100661&format=json"]];
    NSError *error=nil;
    id response=[NSJSONSerialization JSONObjectWithData:data options:
                 NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error];
    if (error) {
        NSLog(@"%@",[error localizedDescription]);
    } else {
     NSDictionary*   _query = [response objectForKey:@"query"];

        dispatch_async(dispatch_get_main_queue(), ^{
            ViewController *vc = (ViewController*)[(UINavigationController*)self.window.rootViewController topViewController];
            vc.query = _query;
        });
    }
    // Override point for customization after application launch.
    return YES;
}

这取决于你把这段代码放在哪里,但最好我们应该把下面的代码放在你的DatashowingViewController的前一个UIViewController中(我的是ViewController)并将信息传递给ViewController(比如我已经完成了),这样我们就可以重复使用相同的UIViewController 来显示相同​​的结果。

我希望这个答案能帮助你实现你的输出。

【讨论】:

  • app 会在 dispatch_async(dispatch_get_main_queue(), ^{ ViewController vc = (ViewController *)[(UINavigationController)self.window.rootViewController topViewController]; vc.query 上崩溃= _query; });
  • 那是向您展示如何在您的 ViewController 中传递响应数据。现在告诉我你的 Viewcontroller 是否作为 UINavigationController 的 topViewController 是应用程序窗口的 rootViewController?
  • 我不能在上面的评论中包含 navigationviewcontroller 和我的代码。
  • 谢谢兄弟,它会起作用我不能在 lodametho 中加载 json url,而不是在应用程序委托中。谢谢。
  • 在这种情况下,不要更改 Web 服务调用的位置。就让它写在它写的地方。现在用 UITableView 制作一个类似的 NewViewcontraoller。编写与此 Viewcontroller 中相同的 tableDatasource 和 Tabledelegate。复制查询、_allkeys 属性和 setter 方法并粘贴到 newviewcontroller 中。现在在 didSlect 方法中用 newviewcontroller 改变 viewcontroller 对象。
猜你喜欢
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多