【问题标题】:How to Read and Use Integer value from Core Data如何从核心数据中读取和使用整数值
【发布时间】:2013-11-09 07:51:39
【问题描述】:

我将重新提出问题:

我使用 Core Data 并将一个具有属性的实体:attribute1 定义为 Integer16

我看了属性:

NSArray *objects = [objectContext executeFetchRequest:request error:&error];

int integer1 = [[objects valueForKey:@"attribute1"] integerValue]

在这最后一句中,应用程序崩溃了。

目的是实现算术:

int integer2 = 0;

integer2 = integer2 + integer1;

也许我必须使用 NSNumber、NSInteger、NSUInteger?

真的,我不明白这么简单的东西怎么用 Objective C 这么复杂。

没有评论...

原问题:

首先,我使用 XCode 5 (iOS 7)

我已将属性 countStep 定义为 Integer 16 的实体。在该属性中,我保存了一个值(即 10)

稍后,我想读取该值:

int integerVal1 = [[objects valueForKey:@"countStep"] integerValue];

意图实现算术运算:

int integerVal2;

integerVal2 = integerVal2 + integerVal1

但在源代码行中:

int integerVal1 = [[objects valueForKey:@"countStep"] integerValue];

应用程序崩溃并显示错误消息:

* 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'-[__NSArrayI integerValue]:无法识别的选择器已发送到实例

我已经尝试了几种替代方法。

@property (nonatomic, assign) int integerVal2;

或者:

NSString *string = [[objects valueForKey:@"countStep"]description];

int integerVal1 = [NSNumber numberWithInteger:[string intValue]];

integerVal2 = integerVal2 + integerVal1

问题是一样的:将字典对象转换为原始元素 int(整数)以计算算术运算:integerVal2 = integerVal2 + integerVal1

有什么想法吗?

【问题讨论】:

  • 错误提示 countStep 是一个数组。它是一个数组吗?你是如何设置值的?您是否向您的实体添加了任何自定义代码?
  • countStep 是 Core Data 中属性的名称。问题是:如何用 Core Data 中保存的整数(即 10、5 或其他)实现求和?
  • 正如您所描述的那样,成为整数 16 是正确的。但是运行时说你还没有这样做——因此是例外。
  • 我会重新提出这个问题。很抱歉造成误解。
  • 如何设置数字并将其保存到核心数据?

标签: core-data xcode5


【解决方案1】:

好的,仔细阅读您的代码...这个:

NSArray *objects = [objectContext executeFetchRequest:request error:&error];

int integer1 = [[objects valueForKey:@"attribute1"] integerValue]

永远不会起作用,因为在数组上调用valueForKey: 会返回一个数组。因此,当您致电 integerValue 时,您会遇到异常。

你应该做的是:

NSArray *objects = [objectContext executeFetchRequest:request error:&error];
id myEntity = objects[0]; // put protection around this...
int integer1 = [[myEntity valueForKey:@"attribute1"] integerValue]

【讨论】:

  • 非常感谢。那是我的问题:如何将返回的数组值(调用 valueForKey)转换为原始值(int)。因为当我看到调试区域时,我看到了被“()”四舍五入的值(3即)。
  • 重复,非常感谢先生。哇!完美运行!关键是:id myEntity = objects[0]; 太糟糕了,我没有找到关于这句话的任何信息,我已经失去了 2 天。重复一遍,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 2012-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多