我创建了一个带有float属性的实体,并将其值设置为0.5

+(void)createSportNamed:(NSString *)name withContext:(NSManagedObjectContext *)context{
Sport *newSport = [NSEntityDescription insertNewObjectForEntityForName:@"Sport" inManagedObjectContext:context];
    newSport.name = name;
    newSport.maxRep = [NSNumber numberWithInt:45];
    newSport.endurance = [NSNumber numberWithFloat:0.5f];
    NSLog(@"endurance at set = %f",[newSport.endurance floatValue]);

NSError *saveError = nil;
[context save:&saveError];
}


从日志中,浮点值仍为0.5000

但是当我以后取它时,该值以某种方式变为0.0000

-(NSArray*)createWorkoutForSport:(NSString*)sportName withContext:(NSManagedObjectContext*)context{

NSFetchRequest *request = [NSFetchRequest new];
request.entity = [NSEntityDescription entityForName:@"Sport" inManagedObjectContext:context];
NSPredicate *sportNamePredicate = [NSPredicate predicateWithFormat:@"name == %d",sportName];
request.predicate = sportNamePredicate;
NSError *err = nil;
NSArray *results = [context executeFetchRequest:request error:&err];
Sport *theFetchedSport = [results lastObject];

int totalRep = [[theFetchedSport maxRep]intValue];
float endure = [[theFetchedSport endurance]floatValue];
int set;
NSLog(@"Endurance = %f",endure);

最佳答案

+(void)createSportNamed:(NSString *)name withContext:(NSManagedObjectContext *)context{
  Sport *newSport = [NSEntityDescription insertNewObjectForEntityForName:@"Sport" inManagedObjectContext:context];
  newSport.name = name;


这清楚地表明您的Sport实体的“名称”字段是一个字符串。

[NSPredicate predicateWithFormat:@"name == %d",sportName]


但是这里您使用的是%d,即int。您正在将字符串指针转换为int。您应该使用%@。因此,您的获取请求返回一个空数组,而-lastObject返回nil,这意味着[nil endurance]也是nil,这意味着[[nil endurance] floatValue]也是nil0

关于iphone - 从核心数据中提取时, float 金额变为0.0000,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10568966/

10-11 14:49