我使用以下代码在表格中显示我的数据中的kg vs lbs。
由于某种原因,它无法正常工作并且给了我很多数字。有什么想法吗?
我正在使用DDUnitConverter (https://github.com/davedelong/DDUnitConverter)
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSString *repsText = [[managedObject valueForKey:@"reps"] description];
NSNumber *weightInPounds = [NSNumber numberWithFloat:[[managedObject valueForKey:@"weight"]floatValue]];
NSNumber *weightInKilos = [[DDUnitConverter massUnitConverter] convertNumber:weightInPounds fromUnit:DDMassUnitUSPounds toUnit:DDMassUnitKilograms];
NSString *weightText = nil;
NSString *cellText = nil;
BOOL isKgs = [[NSUserDefaults standardUserDefaults] boolForKey:@"wantsKGs"];
if (isKgs == 1)
{
weightText = [[NSString alloc]initWithFormat:@"%i", weightInKilos];
cellText = [[NSString alloc]initWithFormat:@"Set %i: %@ reps at %@ kgs",indexPath.row + 1, repsText, weightText];
}
else
{
weightText = [[NSString alloc]initWithFormat:@"%i", weightInPounds];
cellText = [[NSString alloc]initWithFormat:@"Set %i: %@ reps at %@ lbs",indexPath.row + 1, repsText, weightText];
}
cell.textLabel.text = cellText;
}
答案 0 :(得分:2)
哦,这是一个容易解决的问题。 weightInKilos
和weightInPounds
是NSNumber
个实例。在格式中使用%i
格式化程序时,表示您正在提供整数。您最终提供的整数是每个对象的指针值。由于您需要每个NSNumber的字符串值,因此请使用实例方法-stringValue
。
以下是基于这些更改的代码更新版本。
- (void) configureCell: (UITableViewCell *) cell atIndexPath: (NSIndexPath *) indexPath
{
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath: indexPath];
NSString *repsText = [[managedObject valueForKey: @"reps"] description];
NSNumber *weightInPounds = [NSNumber numberWithFloat: [[managedObject valueForKey: @"weight"] floatValue]];
// Alternatively you could just use ‘[managedObject valueForKey: @"weight"]’ if the ‘weight’ attribute is a number.
NSNumber *weightInKilos = [[DDUnitConverter massUnitConverter] convertNumber: weightInPounds
fromUnit: DDMassUnitUSPounds
toUnit: DDMassUnitKilograms];
BOOL isKgs = [[NSUserDefaults standardUserDefaults] boolForKey:@"wantsKGs"];
NSString *weightText = (isKgs ? [weightInKilos stringValue] : [weightInPounds stringValue]);
cell.textLabel.text = [NSString stringWithFormat: @"Set %i: %@ reps at %@ lbs",indexPath.row + 1, repsText, weightText];
}
请记住,在处理对象时必须遵循内存管理规则。使用-init...
方法创建对象时,必须确保将其释放。在您的代码中,这意味着weightText
和cellText
。
PS:DDUnitConverter是一个很棒的发现。如果我在将来的项目中需要它,我将不得不将它加入书签。