【问题标题】:dictionary not created properly?字典没有正确创建?
【发布时间】:2017-07-22 00:20:46
【问题描述】:

我正在使用下面的代码在应用程序中创建一个 nsdictionary。

  NSDictionary *allImportDict = [[NSDictionary alloc] initWithObjectsAndKeys:
                            [NSNumber numberWithInt:containerId], @"containerId",
                                 [NSNumber numberWithInt:docTypeId], @"docTypeId",filextension, @"fileExt",metaDataFiellds, @"metaDataFields",[NSNumber numberWithInt:tmpRepoId], @"repositoryId",[NSNumber numberWithInt:1], @"pagesCount",
                                 tmpSessionID, @"sessionId", fileName, @"title",guid, @"tmpFileName",[NSNumber numberWithInt:tmpUserID], @"userId",
                            nil];

但它创建字典如下

allImportDict 的打印说明:

{
    containerId = 2;
    docTypeId = 1;
}

请指导我为什么它不包括所有键,因为大多数键都丢失了?

【问题讨论】:

  • 检查你的filextension, @"fileExt"
  • 这有什么问题?
  • filextension好像是nil,然后停止构造字典。
  • 如果使用短语法:=@{@"containerId":[NSNumber numberWithInt:containerId],andSo On},会崩溃。但是对于initWithObjectsAndKeys:,它将在第一个 nil 值处停止。 “这就是为什么”你自己把nil放在最后。
  • @iOSGuy - 如果您有疑问,请添加静态数据并检查

标签: ios objective-c xcode dictionary nsdictionary


【解决方案1】:

您的 NSDictionary “fileExt”参数包含“nil”值。请更新并检查。

【讨论】:

    【解决方案2】:

    我刚刚为值添加了验证,并将NSDictionary 替换为NSMutableDictionary。任何空值都可能破坏您的代码。您只需复制粘贴以下代码即可。

    NSMutableDictionary *allImportDict = [[NSMutableDictionary alloc] init];
    
        if(containerId) {
            [allImportDict setObject:[NSNumber numberWithInt:containerId] forKey:@"containerId"];
        }
    
        if(docTypeId) {
            [allImportDict setObject:[NSNumber numberWithInt:docTypeId] forKey:@"docTypeId"];
        }
    
        if([self canUseString:filextension]) {
            [allImportDict setObject:filextension forKey:@"fileExt"];
        }
    
        if([self canUseString:metaDataFiellds]) {
            [allImportDict setObject:metaDataFiellds forKey:@"metaDataFiellds"];
        }
    
        if(tmpRepoId) {
            [allImportDict setObject:[NSNumber numberWithInt:tmpRepoId] forKey:@"tmpRepoId"];
        }
    
        [allImportDict setObject:[NSNumber numberWithInt:1] forKey:@"pagesCount"];
    
        if([self canUseString:tmpSessionID]) {
            [allImportDict setObject:tmpSessionID forKey:@"sessionId"];
        }
    
        if([self canUseString:fileName]) {
            [allImportDict setObject:fileName forKey:@"fileName"];
        }
    
        if([self canUseString:guid]) {
            [allImportDict setObject:guid forKey:@"guid"];
        }
    
        if(tmpUserID) {
            [allImportDict setObject:[NSNumber numberWithInt:tmpUserID] forKey:@"userId"];
        }
    
        NSLog(@"allImportDict: %@", allImportDict);
    

    【讨论】:

      猜你喜欢
      • 2012-02-17
      • 1970-01-01
      • 2017-05-25
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-19
      相关资源
      最近更新 更多