0

我创建了一个具有浮点属性的实体并将其值设置为 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];
}

从日志看,float的值还是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);
4

1 回答 1

2
+(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。你应该使用%@. 因此,您的 fetch 请求返回一个空数组,并且-lastObject正在返回nil,这意味着 that [nil endurance]is nil,这意味着 that [[nil endurance] floatValue]is nil,或0

于 2012-05-13T02:54:09.867 回答