问题描述
||
我正在使用以下代码在表中显示数据的公斤和磅。
由于某种原因,它无法正常工作,并给了我大量的信息。有任何想法吗?
我正在使用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\",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];
}
请记住,处理对象时必须遵循内存管理规则。使用“ 7”方法创建对象时,必须确保将其释放。在您的代码中表示means8ѭ和cellText
。
PS:DDUnitConverter是一个很好的发现。如果以后的项目中需要,我必须将其保留为书签。