【问题标题】:Unable to create dictionary in objective c?无法在目标 c 中创建字典?
【发布时间】:2017-02-24 12:21:17
【问题描述】:

我无法在目标 c 中创建字典。我收到警告

不兼容的整数到指针的转换将nsinteger发送到参数

下面是我的代码。

 NSString *tmpSessionID = [[[AppSettings sharedAppSettings] getUserSession] objectForKey:@"UserSessionId"];
  int tmpRepoId = [[[[AppSettings sharedAppSettings] getUserRepository] objectForKey:@"RepositoryId" ]intValue];
  int tmpUserID = [[[[AppSettings sharedAppSettings] getUserSession] objectForKey:@"UserId"]intValue];
  NSDictionary * fmDic = [[AppSettings sharedAppSettings] getFolderModel];
  int containerId = containerId = [[fmDic objectForKey:@"ContainerId"]intValue];
  int docTypeId = selectedDcoumentType.docTypeId;
  NSDictionary *metaData = [[NSDictionary alloc] initWithObjectsAndKeys:
                       selectFileIndices.columnId, @"ColumnId",
                       indexValue, @"Value",
                       nil];
  NSMutableArray *metaArray  = [[NSMutableArray alloc]init];
  [metaArray addObject:metaData];
  NSDictionary *metaDataFiellds = [[NSDictionary alloc] initWithObjectsAndKeys:
                                   metaArray, @"metaDataFields",
                                   nil];

  NSDictionary *allImportDict = [[NSDictionary alloc] initWithObjectsAndKeys:
                            containerId, @"containerId",
                            docTypeId, @"docTypeId",selectFileIndices.transText, @"fileExt",metaDataFiellds, @"metaDataFields",tmpRepoId, @"repositoryId",1, @"pagesCount",
                                 tmpSessionID, @"sessionId", @"1487918350642.jpg", @"title",guid, @"tmpFileName",tmpUserID, @"userId",
                            nil];
  NSLog(@"dictionary is %@",allImportDict);

我想创建一个如下所示的 json:

{
  "containerId": 2,
  "docTypeId": 1,
  "fileExt": ".jpg",
  "metaDataFields": [
    {
      "ColumnId": 1,
      "Value": "23"
    }
  ],
  "pagesCount": 1,
  "repositoryId": 1,
  "sessionId": "1587c3c9-f261-4749-ace4-c134d031ec38",
  "title": "1487918350642.jpg",
  "tmpFileName": "5f8a0340-bd65-476c-b377-67fa19121203",
  "userId": 5
}

【问题讨论】:

  • 哪一行出错了
  • NSDictionary 不能存储标量值(如 BOOL、NSInteger 等),它只能存储对象。您必须将标量值包装到 NSNumber 中以存储它们:[NSNumber numberWithInteger containerId]
  • 你知道现在没有人像这样写Objective-C。你听说过字典文字或下标访问吗?

标签: ios objective-c dictionary xcode6


【解决方案1】:

NSDictionary 只接受对象,不接受基本类型。您需要将 int 包装在 NSNumber 中

[NSNumber numberWithInt:tmpRepoId]

或者,在现代 Obj-C 中:

@(tmpRepoId)

并将其添加到字典中。

一般来说,我建议使用现代 Obj-C 以获得更好的可读性,例如:

int containerId fmDic[@"ContainerId"].intValue;
NSDictionary *metaDataFiellds = @{ @"metaDataFields" : metaArray };

还可以考虑使用 NSInteger 而不是 int。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 2017-04-19
    • 2019-05-25
    • 1970-01-01
    相关资源
    最近更新 更多