【问题标题】:Why isn't my code to fill a dictionary(and tableview) working?为什么我的填充字典(和表格视图)的代码不起作用?
【发布时间】:2014-02-03 15:19:14
【问题描述】:

当我的 iOs 应用程序被加载时,它会检查它是否是应用程序的第一次加载,如果是,则为 tableview 设置默认单元格。但是,代码不起作用。

在我看来确实加载了:

NSDictionary *dict;

//if the app HASN'T loaded before
if(![[NSUserDefaults standardUserDefaults] boolForKey:@"hasLoaded"])
{
    //note that the app has loaded
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasLoaded"];

    //set the defaults

    //value1
    [dict setValue:@"some string" forKey:@"one"];

    [[NSUserDefaults standardUserDefaults] setValue:dict forKey:@"tableCells"];
}

//now add all to the table view
[tableView insertRowsAtIndexPaths:[[[NSUserDefaults standardUserDefaults] objectForKey:@"tableCells"] allKeys] withRowAnimation:UITableViewRowAnimationFade];

我想要做的是,当我的应用第一次加载时,设置一些带有关联值的默认值。但是,当我使用 NSLog(@"%@", [dict allKeys]) 记录字典的键时,在设置键后立即得到 null。

编辑 1:尝试了一些答案,现在我在使用 NSLog 时得到了一些东西,但是我的 tableview 没有被填充。

编辑 2:一切正常,谢谢!

【问题讨论】:

  • 如果tableView有问题,贴出相关代码。
  • @etolstoy 你是什么意思?就我而言,我有(底线)。
  • 好吧,为了让你的 tableView 工作,你必须实现 UITableViewDelegate 方法,例如 numberOfRows 和 cellForRowAtIndexPath。
  • 哦...我还不太了解,我一直在尝试从静态单元格中移动(在情节提要中设置,为此我不得不从代码中删除一些方法)到从默认值加载的值。我会多读一点
  • 是的,阅读一些关于 UITableViews 的教程。您现在可以关闭此问题并将其中一个答案标记为已接受。

标签: ios dictionary


【解决方案1】:

您必须使用setObject: 而不是setValue:

[dict setObject:@"some string" forKey:@"one"];

别忘了打电话:

NSMutableDictionary *dict = [NSMutableDictionary new];

感谢@Bruno 对NSMutableDictionary 的评论。

【讨论】:

    【解决方案2】:

    看起来您从未创建过NSDictionary,所以dict 将是空的。

    【讨论】:

    • 而且它必须是 NSMutableDictionary。
    【解决方案3】:

    您还没有创建 dict 的实例。试试

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    

    【讨论】:

      猜你喜欢
      • 2022-12-10
      • 2017-04-30
      • 1970-01-01
      • 1970-01-01
      • 2016-02-08
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 2014-01-23
      相关资源
      最近更新 更多