Coredata Float数字变为零

时间:2010-12-05 00:51:38

标签: ios core-data floating-point nsnumber

我遇到了一个无法用Core Data实体解决的问题。

在我的实体中有两个关系(whoHasToPay,whoHasToBePaid)和一个属性(howMuch)。

这是我在数据库中插入记录的代码

Debitcredit *dc = [NSEntityDescription
  insertNewObjectForEntityForName:@"Debitcredit"
  inManagedObjectContext:self.context];
dc.howMuch = [NSNumber numberWithFloat:5.2f];
dc.whoHasToPay = theDebitor;
dc.whoHasToBePaid = theCreditor;
NSLog(@"%@", dc);
[self.context save:&error];

NSLog显示

<Debitcredit: 0x151590> (entity: Debitcredit; id: 0x141570 
  <x-coredata:///Debitcredit/t8DC4691F-5DE3-42D5-8095-C2D5D3264C8D2> ; data: {
  howMuch = "5.2";
  whoHasToBePaid = "0x140c50 <x-coredata://C25DC4FE-B46B-402C-B513-A2A83C6A9F86/Users/p1>";
  whoHasToPay = "0x14c280 <x-coredata://C25DC4FE-B46B-402C-B513-A2A83C6A9F86/Users/p2>";
})

因此值howMuch似乎是正确的。

但是,当我再次使用

调用它时
fetchRequestCount = [[NSFetchRequest alloc] init];
entityCount = [NSEntityDescription entityForName:@"Debitcredit"      
  inManagedObjectContext:self.context];
[fetchRequestCount setEntity:entityCount];
fetchedObjectsCount = [self.context executeFetchRequest:fetchRequestCount error:&error];
for (Debitcredit *dc in fetchedObjectsCount) {
    NSLog(@"%f", [dc valueForKey:@"howMuch"]);
    NSLog(@"%@", [[dc valueForKey:@"whoHasToPay"] name]);
    NSLog(@"%@", [[dc valueForKey:@"whoHasToBePaid"] name]);
}
[fetchRequestCount release];

NSLog显示

2010-12-05 01:47:04.636 myApp[6179:307] 0.000000
2010-12-05 01:47:04.642 myApp[6179:307] John
2010-12-05 01:47:04.646 myApp[6179:307] Jack

似乎howMuch已变为零。为什么?我错了吗?

1 个答案:

答案 0 :(得分:3)

这是一个日志记录错误。浮点数和其他数值存储为NSNumber对象。这样:

[dc valueForKey:@"howMuch"]

...返回NSNumber对象而不是浮点值。您需要将日志更改为:

NSLog(@"%@", [dc valueForKey:@"howMuch"]);

......你应该看到正确的价值。