문제

Simple question, i think...

How can I add up the values in the following string? scoreValue = "8.68,2.815,5,7.975,2.695,7.285,3.625,7.36,8.335,2.485";

Bit of background info. The string is returned from a CoreData entity (called "ScoreData"), and put into an instance of NSDictionary, like this:

NSDictionary *getScoreValues = [self.scoreEntityResultsForValues objectAtIndex:[indexPath row]];
NSLog(@"getScoreValues returns: %@", getScoreValues); // This is what getScoreValues returns for each of the scoreValue's in the CoreData entity.

This is how the value's are posted to the entity initially

//Call the ScoreData entity
ScoreData *newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"ScoreData" inManagedObjectContext:self.managedObjectContext];

//Join the value returned from the NSArray by a "," and post them as a string to the ScoreData entity
NSString *stringForScoreEntity = [[CEWStoreVars sharedScoreArray].sharedScoreArrayProperty componentsJoinedByString:@","];
newEntry.scoreValue = stringForScoreEntity;

The reason I post the values as a string to the entity, is because I couldn't get the entity to accept a float value, and I want to be able to pull out each seperate score later on. But I'm open to suggestions if there is a better method of doing this. Also, let me know if you need more code to decipher what's going on!

Thanks in advance!

EDIT

For anyone interested, this is how the code should look:

//Load the Key and KeyValue into Dictionary
NSDictionary *getScoreValues = [self.scoreEntityResultsForValues objectAtIndex:[indexPath row]];

//Convert the dictionary keyValue to a string
NSString *convertDictKeyToString  = [getScoreValues objectForKey:@"scoreValue"];

//Remove the "," in the string.
NSArray *items = [convertDictKeyToString componentsSeparatedByString:@","];

//Add them up to get the sum
double total = 0.0;
for (NSString *string in items)
{
    total += [string floatValue];
}
도움이 되었습니까?

해결책

NSArray *items = [scoreValue componentsSeparatedByString:@","]; //scoreValue is a string

double total = 0.0;
for (NSString *string in items)
{
    total += [string floatValue];
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top