Get values from an Array and calc - objective-c

I have an array width this values:
array: (
{
id = 1;
name = "Cursus Nibh Venenatis";
value = "875.24";
},
{
id = 2;
name = "Elit Fusce";
value = "254.02";
},
{
id = 3;
name = "Bibendum Ornare";
value = "123.42";
},
{
id = 4;
name = "Lorme Ipsim";
value = "586.24";
}
)
What I need to do is get each 'value' and sum it all. Im declaring a new array to take each value:
self.valuesArray = [[NSArray alloc] init];
But how can I do it? Thanks for your answer!

double sum = [[array valueForKeyPath:#"#sum.value"] doubleValue];
You can read more on collection operators here

You have already declared array so i will use your. I also assume your first array(which contains data set above) is an array called myFirstArray(of type NSArray)
int sum =0;
self.valuesArray = [[NSMutableArray alloc] init];
for(NSDictionary *obj in myFirstArray){
NSString *value =[obj objectForKey:#"value"];
sum+= [value intValue];
[self.valuesArray arrayWithObject:value];//this line creates a new NSArray instance which conains array of 'values'(from your dictionary)
}
NSLog("The sum of values is: %d", sum);
NSLog("The array of \'values\' is : %#",self.valuesArray );

double sum=0.0;
for (YourDataObject *d in array) {
sum+=[[d getValue] doubleValue];
}

try this -
float totalValue = 0.0f;
for (int i = 0 ; i< [array count]; i++) {
totalValue +=[[[array objectAtIndex:i] objectForKey:#"value"] floatValue];
}

Related

Converting String to Character to Integer

I am trying to take a string (#"12345") and extractor each individual character and convert to it's decimal equivalent.
#"1" = 1
#"2" = 2
etc.
Here is what I have this far:
...
[self ArrayOrder:#"1234"];
...
-(void)ArrayOrder(Nsstring *)Directions
{
NSString *singleDirections = [[NSString alloc] init];
//Loop Starts Here
*singleDirection = [[Directions characterAtIndex:x] intValue];
//Loop ends here
}
I have been receiving type errors.
The problem with your code is that [Directions characterAtIndex:x] returns a unichar, which is a Unicode character.
Instead, you can use NSRange and substrings to get each number out of the string:
NSRange range;
range.length = 1;
for(int i = 0; i < Directions.length; i++) {
range.location = i;
NSString *s = [Directions substringWithRange:range];
int value = [s integerValue];
NSLog(#"value = %d", value);
}
Another approach would be to use / 10 and % 10 to get to each number from the string individually. Such as:
NSString* Directions = #"1234";
int value = [Directions intValue];
int single = 0;
while(value > 0) {
single = value % 10;
NSLog(#"value is %d", single);
value /= 10;
}
However, that goes through your string backwards.

Compare two items in one NSArray

I have an array containing twenty items. I want to search through the array, comparing one item to the next one in the array, and then print the larger item. I have already sorted the array. I just want to compare the two items, check what the remainder is between the two values, and if it's greater than say, four, print the larger item.
NSArray* arr = [NSArray arrayWithObjects:
[NSNumber numberWithInt:1],
[NSNumber numberWithInt:6],
[NSNumber numberWithInt:7],
[NSNumber numberWithInt:11],
nil
];
int len = [arr count];
for (int i=0; i < len-1; ++i) {
int num1 = [[arr objectAtIndex:i] intValue];
int num2 = [[arr objectAtIndex:i+1] intValue];
if ( num2-num1 > 4 ) {
NSLog(#"%d", num2);
}
}
--output:--
6
NSEnumerator *itemEnumerator = [theArray objectEnumerator];
YourClass *lastObject = [itemEnumerator nextObject];
YourClass *compareObject;
while( (compareObject = [itemEnumerator nextObject]) != nil)
{
if( /* place your condition here */ )
{
NSLog( … );
}
lastObject = compareObject;
}
Typped in Safari

How to parse JSON

How to parse this below "choices" on one array means when I have get "id" in array that all id values 108,109.... in 1st index in array but here is the 5 values in choices..so how to parse it
choices = (
{
id = 108;
label = Distributor;
},
{
id = 109;
label = "Clinical Lab";
},
{
id = 110;
label = Researcher;
},
{
id = 111;
label = "Current Customer";
},
{
id = 112;
label = "Past Customer";
}
);
Get in a single Step bro as
If your array is NSMutableArray then use as
NSArray *resultArray = [[NSArray arrayWithArray:temp] valueForKeyPath:#"id"]
If simple NSArray then use as
NSArray *resultArray = [jsonArray valueForKeyPath:#"id"]
You can do it using fast enumeration.
NSMutableArray *resultArray = [[NSMutableArray alloc] initWithCapacity:0];
// JSONDict is your JSON dict
for (NSDictionary *aDict in JSONDict[#"choices"]) {
[resultArray addObject:aDict[#"id"]];
}
NSLog(#"%#", resultArray);
Output:
(
108,
109,
110,
111,
112
)
If i understand your question properly, Then You can try this code for getting Ids in a Array:
NSMutableArray *arr = [[NSMutableArray alloc] init];
for (int i = 0;i<[choices count];i++)
{
[arr addObject:[[choices objectAtIndex:i] objectForKey:#"id"]];
}
NSLog(#"ID array : %#",arr);
[arr release];
try like this ,
NSMutableArray *idArray=[[NSMutableArray alloc]init];
for(int i=0;i<[jsonArray count];i++)
[idArray addObject:[[jsonArray objectAtIndex:i] valueForKey:#"id"]];
NSLog(#"%#",idArray);
here you'l get all the values in idArray.

EXC_BAD_ACCESS on getting value from NSValue

I'm constructing a series of MKPolygons and storing them in an array of NSValues:
for (NSDictionary* country in countries) {
NSMutableArray* polygons = [[NSMutableArray alloc] init];
for (NSArray* polygon in [country objectForKey:#"polygons"]) {
CLLocationCoordinate2D polygonCoords[polygon.count];
int i;
for (i = 0; i < polygon.count; i++) {
NSValue* coords = [polygon objectAtIndex:i];
CLLocationCoordinate2D stored_coords;
[coords getValue:&stored_coords];
polygonCoords[i] = stored_coords;
}
MKPolygon* poly = [MKPolygon polygonWithCoordinates:polygonCoords count:polygon.count];
[polygons addObject:[NSValue valueWithBytes:&poly objCType:#encode(MKPolygon)]];
[chillPillMap addOverlay:poly];
}
[country setValue:polygons forKey:#"polygon_objects"];
}
However, when I try to access them later, I get two or three in and a EXC_BAD_ACCESS occurs:
for (NSDictionary* country in countries) {
NSArray* polygon_objects = [country objectForKey:#"polygon_objects"];
int i;
for (i = 0; i < polygon_objects.count; i++) {
MKPolygon* saved_poly = [MKPolygon alloc];
[[polygon_objects objectAtIndex:i] getValue:&saved_poly];
}
}
Not sure why this is.
MKPolygon is an objective-C object. You can put it into the array without converting it to a NSValue. Furthermore, you are telling NSValue to take the value of the bytes, but you are passing it the address of the pointer. Bad news.
Why not just...
[polygons addObject:poly]
then...
MKPolygon *saved_poly = [polygon_objects objectAtIndex:i];

[OBJ-C][iOS] Getting floating point from NSArray - Problem

I’ve recently stuck at a problem. Here is the thing, I’m trying to get a float object from NSArray that holds it, and all I can get is (null). Obviously not the thing that I want to receive. Look at the snippet of code:
h = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:1.0], nil];
x = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithFloat:1.0],[NSNumber numberWithFloat:2.0], nil];
y = [[NSMutableArray alloc] init];
int step = 15; // That is just a random value, will depend on size of h and x.
for (int i = 0; i < step; ++i) {
NSLog(#"step = %i", i);
NSMutableArray *xTemp = [[NSMutableArray alloc] initWithArray:x];
NSMutableArray *hTemp = [[NSMutableArray alloc] initWithArray:h];
for (int j = 0; j < 3; ++j) {
float xToMul = [[xTemp objectAtIndex:j] floatValue];
float hToMul = [[hTemp objectAtIndex:(j+i)] floatValue];
NSLog(#"xToMul = %#", xToMul);
NSLog(#"hToMul = %#", hToMul);
}
NSLog(#"\n");
}
And the resul is:
xToMul = (null)
hToMul = (null)
and all I need those values is to do some easy math.
Thanks.
M.R.
Here's your problem:
float xToMul = [[xTemp objectAtIndex:j] floatValue]; float hToMul = [[hTemp objectAtIndex:(j+i)] floatValue];
NSLog(#"xToMul = %#", xToMul); NSLog(#"hToMul = %#", hToMul);
%# is for objects that support -description. float is not an object at all. This code sends the float a -description message, which it can't respond to.
There's two ways to solve this.
The first is to make xToMul and hToMul objects instead of floats and keep the format string.
id xToMul = [xTemp objectAtIndex:j];
id hToMul = [hTemp objectAtIndex:(j+i)];
NSLog(#"xToMul = %#", xToMul);
NSLog(#"hToMul = %#", hToMul);
The second is to keep them as floats but fix the format string:
float xToMul = [[xTemp objectAtIndex:j] floatValue];
float hToMul = [[hTemp objectAtIndex:(j+i)] floatValue];
NSLog(#"xToMul = %f", xToMul);
NSLog(#"hToMul = %f", hToMul);
If you're planning to do math with the floats, you probably want to pick this option.
Another interesting point is this loop:
for (int j = 0; j < 3; ++j) {
This will step through j with three values: 0, 1 and 2. That corresponds to the first, second and third item in NSArray. You have two items in x and three in h. I'm guessing this is just a simplification of your original code, but in both cases it's one short. j of 2+1 will access the 4th item in h, and j of 2 will access the 3rd item in x.