i have a loop in Objective C and i compare two index of the same array but the comparison doesnt work ,there is no compile error. Variable iMinor is always zero and arrayDistancias is not empty:
NSMutableArray *arrayDistancias = [NSMutableArray array];
NSNumber *lat1 = [NSNumber numberWithFloat:39.0025];
NSNumber *lat2 = [NSNumber numberWithFloat:40.2710];
NSNumber *lat3 = [NSNumber numberWithFloat:38.5316];
NSNumber *lat4 = [NSNumber numberWithFloat:27.4529];
NSNumber *lng1 = [NSNumber numberWithFloat:-1.5139];
NSNumber *lng2 = [NSNumber numberWithFloat:-3.4327];
NSNumber *lng3 = [NSNumber numberWithFloat:-7.0029];
NSNumber *lng4 = [NSNumber numberWithFloat:-15.3432];
//for (NSInteger i = 0; i < 40; i++)
[arrayDistancias addObject:[NSNumber numberWithInteger:[self calcularDistancia:latitudaqui :lat1 :longitudaqui :lng1]]];
[arrayDistancias addObject:[NSNumber numberWithInteger:[self calcularDistancia:latitudaqui :lat2 :longitudaqui :lng2]]];
[arrayDistancias addObject:[NSNumber numberWithInteger:[self calcularDistancia:latitudaqui :lat3 :longitudaqui :lng3]]];
[arrayDistancias addObject:[NSNumber numberWithInteger:[self calcularDistancia:latitudaqui :lat4 :longitudaqui :lng4]]];
int iMinor = 0;
for (int i = 0; i < [arrayDistancias count]; i++) {
if([arrayDistancias objectAtIndex: i] < [arrayDistancias objectAtIndex: iMinor]){
iMinor = i;
}
}
thanks in advance
[arrayDistances objectAtIndex: i] retuns the NSNumber object, not the integer value. In order to get the integer value use intValue method on the returned object. So, you should compare it like this.
if ([[arrayDistances objectAtIndex: i] intValue] <
[[arrayDistances objectAtIndex: iMinor] intValue]) {
Related
for(int i=0; i<[arrMaintenanceDetail count]; i++){
for(int j=0; j<[[arrMaintenanceCategory valueForKey:#"maintenanceCategory"] count]; j++){
if([[arrMaintenanceDetail objectAtIndex:i] isEqualToString:[[[arrMaintenanceCategory valueForKey:#"maintenanceCategory"]objectAtIndex:i] stringValue]]){
[arrTotalValues objectAtIndex:i] += [arrTotalValues insertObject:[[[arrMaintenanceCategory valueForKey:#"cost"] objectAtIndex:j] integerValue] atIndex:i];
}
}
}
I want to add (make addition of integer values) value from
[[[arrMaintenanceCategory valueForKey:#"cost"] objectAtIndex:j] integerValue];
Whenever loop changes its value.
I want new value from objectAtIndex:j to be added to its previous value and store it for future use.
I will have 4 objects in arrTotalValues (NSMutableArray).
So what should I do ??
You cannot keep integers in NSMutableArray. Use NSNumber to keep integer values in your NSMutableArray as objects.
You didn't provide enough information to give you 100% working code, but try something like that:
NSMutableArray* arrTotalValues = [NSMutableArray array];
for(int i=0; i<[arrMaintenanceDetail count]; i++)
{
NSNumber* totalValue = [NSNumber numberWithInt:0];
for(int j=0; j<[[arrMaintenanceCategory valueForKey:#"maintenanceCategory"] count]; j++)
{
if([[[arrMaintenanceDetail objectAtIndex:i] stringValue] isEqualToString:[[[arrMaintenanceCategory valueForKey:#"maintenanceCategory"] objectAtIndex:i] stringValue]])
{
int newTotalValue = [totalValue intValue] + [[[arrMaintenanceCategory valueForKey:#"cost"] objectAtIndex:j] integerValue];
totalValue = [NSNumber numberWithInt:newTotalValue];
}
}
[arrTotalValues addObject:totalValue];
}
I have a simple looking piece of code that has me completely flummoxed.
NSInteger ymax;
NSInteger ymin;
NSInteger numberIndex1;
NSInteger numberIndex2;
for (NSNumber *theNumber in array2)
{
if ([theNumber integerValue] > ymax) {
ymax = [theNumber integerValue];
numberIndex1 = [array2 indexOfObject:theNumber];
}
}
for (NSNumber *theNumber in array2)
{
if ([theNumber integerValue] < ymin) {
ymin = [theNumber integerValue];
numberIndex2 = [array2 indexOfObject:theNumber];
}
}
NSLog(#"Highest number: %d at index: %d", ymax, numberIndex1);
NSLog(#"Lowest number: %d at index: %d", ymin, numberIndex2);
The NSLog is outputted as:
Highest number: 129171656 at index: -1073752392 (Huh??)
Lowest number: 57 at index: 5 (Correct)
How do you explain this odd behaviour? Both the functions look the same. One is working and one isn't? I've played around a lot with this, but I still can't put my finger on it. Any help would be appreciated/
You can get maximum and minimum number as below code. It may help you
NSNumber * max = [array2 valueForKeyPath:#"#max.intValue"];
NSNumber * min = [array2 valueForKeyPath:#"#min.intValue"];
NSUInteger numberIndex1 = [array indexOfObject:min];
NSUInteger numberIndex2 = [array indexOfObject:max];
NSLog(#"Max Value = %d and index = %d",[max intValue],numberIndex1);
NSLog(#"Min Value = %d and index = %d",[min intValue],numberIndex2);
If I am not wrong you are considering the default value of NSInteger is 0, No, it isn't guaranteed to be zero, since it's a local automatic variable. Without initialization, its value is indeterminate.
so you need to set default values for your var, start with ymax = -1;
Please initialize NSInteger ymax = 0;
NSInteger ymin = 0 ;
NSInteger numberIndex1 = 0;
NSInteger numberIndex2 = 0;
It will fix your issue.
Otherwise it is checking with a garbage value and giving wrong result.
enjoy with my answer.......happy coding
NSArray *arr1=[[NSArray alloc]initWithObjects:#"0.987",#"0.951",#"0.881",#"0.784",#"0.662",#"0.522",#"0.381",#"-0.265",#"-0.197",
#"0.189",#"-0.233",#"0.310",#"0.402",#"0.402",#"0.988",#"0.633",#"0.661",#"0.656",#"0.617",#"0.634",#"0.690",#"0.767",#"0.836",nil];
NSNumber * max = [arr1 valueForKeyPath:#"#max.floatValue"];
NSString *str=[NSString stringWithFormat:#"%#",max];
NSInteger path=[arr1 indexOfObject:str];
NSIndexPath *indepath=[NSIndexPath indexPathForItem:path inSection:0];
NSNumber * min = [arr1 valueForKeyPath:#"#min.floatValue"];
NSString *str1=[NSString stringWithFormat:#"%#",min];
NSInteger path1=[arr1 indexOfObject:str1];
NSIndexPath *indepath1=[NSIndexPath indexPathForItem:path1 inSection:0];
NSLog(#"Max Value = %f and index = %ld",[max floatValue],(long)indepath.row);
NSLog(#"Min Value = %f and index = %ld",[min floatValue],(long)indepath1.row);
A more legitimate solution would be:
NSArray *originalArray = #[[NSNumber numberWithInt:91],
[NSNumber numberWithInt:12],
[NSNumber numberWithInt:99123],
[NSNumber numberWithInt:9],
[NSNumber numberWithInt:43234]];
NSArray *sortedArray = [originalArray sortedArrayUsingSelector:#selector(compare:)];
NSNumber *minNumber = [sortedArray objectAtIndex:0];
NSNumber *maxNumber = [sortedArray lastObject];
NSInteger minIndex = [originalArray indexOfObject:minNumber];
NSInteger maxIndex = [originalArray indexOfObject:maxNumber];
I am getting this data from JSON web services
[{"identity":"DEMO","assets":[{"identity":"34DL3611","systemId":"544507"},{"identity":"34GF0512","systemId":"5290211"},{"identity":"34HH1734","systemId":"111463609"},{"identity":"34HH1736","systemId":"111463622"},{"identity":"34YCJ15","systemId":"294151155"}],"systemId":4921244}]
I am using this method to get the values of assets for identity ("assets":[{"identity":"34DL3611","systemId":"544507"}):
vehicleList = [dict objectForKey: #"assets"];
self.listVehicles = [[NSMutableArray alloc] init];
for (NSUInteger index = 0; index < [vehicleList count]; index++) {
itemDict = [vehicleList objectAtIndex: index];
[self.listVehicles addObject:[itemDict objectForKey:#"identity"]];
}
how can I get the systemId values ... ?
I have tried this for systemId
vehicleListID = [dict objectForKey:#"systemId"];
self.listVehiclesID =[[NSMutableArray alloc]init];
for (NSUInteger index = 0; index < [vehicleListID count]; index++) {
assetsIdDict = [vehicleListID objectAtIndex: index];
[self.listVehiclesID addObject:[assetsIdDict objectForKey:#"systemId"]];
}
but getting error: [__NSCFNumber count]: unrecognized selector sent to instance 0x784c730
You're basically almost there. You just want this probably:
NSString *systemId = [itemDict objectForKey:#"systemId"];
With regard to this code you have:
vehicleListID = [dict objectForKey:#"systemId"];
self.listVehiclesID =[[NSMutableArray alloc]init];
for (NSUInteger index = 0; index < [vehicleListID count]; index++) {
assetsIdDict = [vehicleListID objectAtIndex: index];
[self.listVehiclesID addObject:[assetsIdDict objectForKey:#"systemId"]];
}
... well that is just totally wrong. That's returning the NSNumber which in your example JSON is 4921244 right at the end of the JSON string. You're then calling count on it, but it's not an array, so it crashes.
If you want to get all the values out of that JSON you can use this:
NSNumber *outerIdentity = [dict objectForKey:#"identity"];
NSNumber *outerSystemId = [dict objectForKey:#"systemId"];
NSArray *vehicleList = [dict objectForKey:#"assets"];
for (NSUInteger index = 0; index < [vehicleList count]; index++) {
NSDictionary *itemDict = [vehicleList objectAtIndex: index];
NSString *identity = [itemDict objectForKey:#"identity"];
NSString *systemId = [itemDict objectForKey:#"systemId"];
}
Then do whatever it is you want to do with all those objects.
The json response you are getting is an array. vehicleList should be the objectatIndex 0 of json response.
NSDictionary *vehicleList = [[arrayLoadedFromJson objectAtIndex:0] objectForKey: #"assets"];
vehicleList = [dict objectForKey: #"assets"];
self.listVehicles = [[NSMutableArray alloc] init];
for (NSUInteger index = 0; index < [vehicleList count]; index++) {
itemDict = [vehicleList objectAtIndex: index];
[self.listVehicles addObject:[itemDict objectForKey:#"identity"]];
[self.listVehicles addObject:[itemDict objectForKey:#"systemId"]];
}
This you have to insert:-in your code
[self.listVehicles addObject:[itemDict objectForKey:#"systemId"]];
For that to having in separate array, you need to initialize new NSMutableArray and add the objects.
Else, the better way is, declare a new class with 2 NSString members say, identity and systemId. Extract the values from JSON and assign to the class members. And add that object to the array.
I have the data into the mutable array and the value of array is,
{ "20", "40", "50","60", "70"}.
I have stored the string values into the array.
Now i want to total value of the array. Result is : 240
Thanks!
NSInteger value = 0;
for (String *digit in myArray) {
value += [digit intValue];
}
int total=0;
for(NSString *currentString in myArray){
total +=[currentString intValue];
}
NSLog(#"Sum:%d",total);
This adds all values:
__block NSInteger sum = 0;
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
sum += [obj intValue];
}];
You can do as follows:
int totalSum = 0;
NSmutableArray *arrayData = [[NSmutableArray alloc] init];
[arrayData addObject:#"20"];
[arrayData addObject:#"40"];
[arrayData addObject:#"50"];
[arrayData addObject:#"60"];
[arrayData addObject:#"70"];
for(int i=0; i<[arrayData count];i++)
{
totalSum = totalSum + [[arrayData objectAtIndex:i] intValue];
}
NSLog(#"Total:%d",totalSum);
Please let me know if you have any question.
How about the most elegant solution using key-value Collection aggregators:
NSNumber *sum = [myArray valueForKeyPath:#"#sum.self"];
I am new to iPhone development. I want a Nsmutable array to hold numbers from 1 to 100. How can I do it? How can I implement in a for loop? Is there any other way to hold numbers in array in iPhone?
You can only add NSObject subclasses in Cocoa containers. In your case, you will have to wrap your integers in NSNumber objects:
NSMutableArray *array = [NSMutableArray array];
for( int i = 0; i < 100; ++i )
{
[array addObject:[NSNumber numberWithInt:i]];
}
To extract the values:
int firstValue = [[array objectAtIndex:0] intValue];
Use an NSNumber object:
[NSNumber numberWithInt:1];
The short hand solution
NSMutableArray *array = [NSMutableArray array];
for( int i = 0; i < 100; ++i )
{
[array addObject:#(i)];
}
int intValue = 10;
NSNumber *numberObj = #(intValue);