字典没有正确创建?

时间:2017-03-02 10:18:10

标签: ios objective-c xcode dictionary nsdictionary

我正在使用以下代码在应用中创建一个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;
}

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

2 个答案:

答案 0 :(得分:0)

你的NSDictionary“fileExt”参数包含“nil”value.Plz,更新它并检查。

答案 1 :(得分:0)

我刚刚对值添加了验证,并将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);