我正在使用以下代码在表中显示数据的公斤和磅。
由于某种原因,它无法正常工作,并给了我大量的信息。有任何想法吗?
我正在使用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;
}
最佳答案
哦,这是一个容易解决的问题。 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是一个很好的发现。如果将来的项目中需要,我必须将其保留为书签。