【问题标题】:Why I receive warning in objectForKey method?为什么我在 objectForKey 方法中收到警告?
【发布时间】:2015-05-26 14:05:47
【问题描述】:

我需要在

中执行方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

我有一个NSDictionary,我想从中获取 ID(长)并将其发送到我的方法:

    long sect = (long)section;
    [objectp.methodA countRowsInSection:[tableSections objectForKey:[NSString stringWithFormat:@"%ld", sect]]]

我收到警告:

Incompatible pointer to integer conversion sending 'id' to parameter of type 'long'

为什么?

我尝试将NSInteger 转换为long,然后再转换为NSString,但警告仍然存在。

备注: countRowsInSectionlong

我将NSDictionary中的数据存储为NSString

[tableSections setValue:[NSString stringWithFormat:@"%ld", newCategoryID]
   forKey:[NSString stringWithFormat:@"%ld", counter]];

【问题讨论】:

  • 格式中使用的sect 变量是什么类型的?
  • 对不起@rckoenes,它是long - long sect = (long)section;
  • 尝试溢出该方法,这可能会让您更好地了解错误所在。因为现在我看不出你的代码有什么问题。
  • 仔细查看编译器用来显示错误所在的小箭头。它不是警告您有关教派的信息。它会警告您传递给 countRowsInSection 的对象:

标签: objective-c nsdictionary type-conversion


【解决方案1】:

您的countRowsInSection: 似乎期望它的参数是long。但是您正在向它发送一个对象(可能是NSNumber)。如果是这种情况,以下将起作用:

[objectp.methodA countRowsInSection:[[tableSections objectForKey:[NSString stringWithFormat:@"%ld", sect] longValue]]];

【讨论】:

  • 我还将id 转换为long
【解决方案2】:

我有一个 NSDictionary,我想从中获取 ID(长)并将其发送到我的方法:

不,您不想从字典中获取类型为 long 的 ID,因为 long 是 C 类型,不能存储在字典中。它可能是NSStringNSNumber 的一个实例。然后将其作为-countRowsInSection: 的参数,它可能需要NSIntegerlong,因此是C 类型。

【讨论】:

  • 是的,@Amin Negm-Awad,我将其存储为 NSString: [tableSections setValue:[NSString stringWithFormat:@"%ld", newCategoryID] forKey:[NSString stringWithFormat:@"%ld", counter]];
  • 嗯,这不是最好的主意。您应该使用NSNumber 的实例。但是,如果您的值不超过INT_MAX,您可以使用-intValue 检索long 值。到目前为止,NSNumber 是更好的选择,至少因为您可以使用 @(newCategoryID)-longValue 来检索它。
猜你喜欢
  • 1970-01-01
  • 2011-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多