How do you compare two strings with different format strings? For example, in the code below:
str1 = [dataDic1 objectForKey:[finalArray objectAtIndex:indexPath.row]];
str1 contains 124.00,120/70-14,1,759,140/70-14,48.8 x 57.0.
str2 = [dataDic2 objectForKey:[finalArray objectAtIndex:indexPath.row]];
str2 contains 1.00,90/90-6,1,250,90/90-6,45.3 x 87.0.
I want to compare str1 and str2
if ([bike1Str intValue] < [bike2Str intValue]){
NSLog(#"%#", str2);
}
else{
}
For example: if (120/70-14 < 90/90-6)
How do I do this type comparison ?
DataDic1 {
"Displacement_trim" = "124.00 ";
"Dry_Weight" = "<null>";
"Front_Brakes_Size_trim" = "260 ";
"Front_Tire_Size" = "120/70-14";
"Fuel_Capacity_trim" = "13.50 ";
"Overall_Height_trim" = "1,759 ";
"Overall_Length_trim" = "2,230 ";
Power = "";
"Power_Weight_Ratio" = "<null>";
"Rear_Brake_Size_trim" = "240 ";
"Rear_Tire_Size" = "140/70-14";
Stroke = "";
"Torque_trim" = "";
"stroke_trim" = "48.8 x 57.0 ";
}
and finalArray
(
Power_Weight_Ratio,
Rear_Brake_Size_trim,
Dry_Weight,
Torque_trim,
stroke_trim,
Rear_Tire_Size,
Front_Brakes_Size_trim,
Fuel_Capacity_trim,
Overall_Length_trim,
Front_Tire_Size,
Stroke,
Power,
Displacement_trim,
Overall_Height_trim
)
Not only float values i am asking all the all values to compare
NSMutableDictionary *dict1,*dict2;
NSMutableArray *ArrayContaingFloat;
dict1 = [[NSMutableDictionary alloc]init];
dict2 = [[NSMutableDictionary alloc]init];
ArrayContaingFloat = [[NSMutableArray alloc]init];
[dict1 setObject:[NSNumber numberWithFloat:14.20] forKey:#"Displacement_trim"];
[dict2 setObject:[NSNumber numberWithFloat:20.20] forKey:#"Displacement_trim"];
if ( [[dict1 valueForKey:#"Displacement_trim"] compare:[dict2 valueForKey:#"Displacement_trim"]]==NSOrderedAscending) {
NSLog(#"dict 2 is greater");
}else{
NSLog(#"dict 1 is greater");
}
if( [[dict1 valueForKey:#"Displacement_trim"] compare:[dict2 valueForKey:#"Displacement_trim"]]==NSOrderedAscending){
}
[ArrayContaingFloat addObject:[dict1 valueForKey:#"Displacement_trim"]];
[ArrayContaingFloat addObject:[dict2 valueForKey:#"Displacement_trim"]];
NSLog(#"Array conting float %#",ArrayContaingFloat);
NSSortDescriptor *highestToLowest = [NSSortDescriptor sortDescriptorWithKey:#"self" ascending:NO];
[ArrayContaingFloat sortUsingDescriptors:[NSArray arrayWithObject:highestToLowest]];
NSLog(#"After Sorting %#",ArrayContaingFloat);
you will get output like this:
dict 2 is greater
Array conting float (
"14.2",
"20.2"
)
After Sorting (
"20.2",
"14.2"
)
let me know if you have any further query.
Related
I have an array(seachResult) which contains dictionaries and I want to sort this array according to 'price' key in the dictionary that is a number in string format.
I tried this code but it doesn't work for sorting 'price' but it works for pid which is a number.
how can I sort it according 'price' (number in string format)?
NSSortDescriptor *sortByPrice = [NSSortDescriptor sortDescriptorWithKey:#"price" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByPrice];
NSArray *sortedArray = [self.seachResult sortedArrayUsingDescriptors:sortDescriptors];
NSLog(#"%#",sortedArray );
here is sample data for self.searchResult:
2013-07-17 02:04:55.012 MyApp[57014:16a03] sorted array of dictionaries: (
{
cid = 2;
image = "http:///images/loginlogo.png";
latitude = "48.245565";
longitude = "16.342333";
manual = "";
movie = "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v";
pcode = 023942435228;
pid = 1;
pname = "example product";
price = "12.00";
qrcode = "";
rid = 1;
rname = "Example Retailer Name";
sale = 0;
"sale_percent" = 0;
"sale_price" = "0.00";
text = "here is text about sample product number 1...\nasdasdasda\nsdfsdfsd\nSdfsdf\nSDfsdfs\ndfsdfsdf\n\n\n";
},
{
cid = 2;
image = "http:///testImage.png";
latitude = "48.245565";
longitude = "16.342333";
manual = "";
movie = "";
pcode = 1;
pid = 2;
pname = "sample product 2";
price = "126.00";
qrcode = "";
rid = 1;
rname = "Example Retailer Name";
sale = 1;
"sale_percent" = 20;
"sale_price" = "99.99";
text = "here is text about sample product number 2...\nblah blah blah\nasdasdasd\nASdasdas\nASdasdasd";
},
{
cid = 1;
image = "";
latitude = "";
longitude = "";
manual = "";
movie = "";
pcode = 1;
pid = 3;
pname = "test product";
price = "46.00";
qrcode = "";
rid = 2;
rname = "";
sale = 0;
"sale_percent" = 0;
"sale_price" = "35.00";
text = "some text here...
\nasdasd
\nasd
\na
\nsd
\nas
\nd";
}
)
I also tried this code :
NSSortDescriptor *hopProfileDescriptor =
[[NSSortDescriptor alloc] initWithKey:#"price"
ascending:YES];
NSArray *descriptors = [NSArray arrayWithObjects:hopProfileDescriptor, nil];
NSArray *sortedArrayOfDictionaries = [self.seachResult
sortedArrayUsingDescriptors:descriptors];
NSLog(#"sorted array of dictionaries: %#", sortedArrayOfDictionaries);
but still doesn't work.
I think the issue is that in your self.searchResult array the price data is differently formatted for the objects in the array.
The first object in the array it's formatted like price = 12; (probably a NSDecimalNumber)
The second object in the array it's formatted like price = "125.99"; (proably a NSString)
NSArray *testSorted = [test sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
NSString *price1 = obj1[#"price"];
NSString *price2 = obj2[#"price"];
NSNumber *n1 = [NSNumber numberWithFloat:[price1 floatValue]];
NSNumber *n2 = [NSNumber numberWithFloat:[price2 floatValue]];
return [n1 compare:n2];
}];
Since your price data seems to vary (NSString vs NSNumber) you might try instead using sortedArrayUsingComparator:. eg:
NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
id value1 = [obj1 objectForKey:#"price"];
float float1 = [value1 floatValue];
id value2 = [obj2 objectForKey:#"price"];
float float2 = [value2 floatValue];
if (float1 < float2) {
return NSOrderedAscending;
}
else if (float1 > float2) {
return NSOrderedDescending;
}
return NSOrderedSame;
}];
This is kinda ugly but should get you started. It's also fragile--if you get something other than NSNumber or NSString for the price it'll likely crash.
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.
I am having a requirement in which I have 5 keys stored in a NSDictionary corresponding to which I have stored 5 values from different arrays. My data structure looks like:
Dictionary is {
1 = (
{
SubRegionName = "abc";
WalkId = 123;
WalkName = xyz;
},
{
},....
2 = (
{
SubRegionName = "abc";
WalkId = 123;
WalkName = xyz;
},
{
},....
3 = (
{
SubRegionName = "abc;
WalkId = 123;
WalkName = xyz;
},
{
},....
4 = (
{
SubRegionName = "abc";
WalkId = 123;
WalkName = xyz;
},
{
},....
5 = (
{
SubRegionName = "abc";
WalkId = 123;
WalkName = xyz;
},
{
},
)
The above data I am getting from sqlite according to some Id say tempId(1,2,3,4,5) and I want to use them separately. As I have to display the walkName as cell.textlabel.text and SubregionName as cell.detailtext.text in tableview.
I am not getting how to access this data from the dictionary. Can anyone please suggest me right way to do it.
My code is:
// For Database queries (To get data from database) ***********
-(void)getMainRegions
{
sqlite3 *walkNameDB;
if (sqlite3_open([[self databasePath] UTF8String], &walkNameDB) != SQLITE_OK) {
sqlite3_close(walkNameDB);
NSAssert(0, #"Failed to open Walk name database");
}
NSString *regionQuery = #"SELECT Rid,RName from MainRegions";
sqlite3_stmt *teststatement = nil;
// NSLog(#"%d",sqlite3_prepare_v2(walkNameDB,[regionQuery UTF8String], -1, &teststatement, nil));
if (sqlite3_prepare_v2(walkNameDB,[regionQuery UTF8String], -1, &teststatement, nil) == SQLITE_OK)
{
RNameArray = [[NSMutableArray alloc] init];
RIdArray = [[NSMutableArray alloc] init];
while( sqlite3_step(teststatement) == SQLITE_ROW )
{
NSNumber *RId;
int temp1 = (int)sqlite3_column_int(teststatement, 0);
RId = [[NSNumber alloc] initWithInt:temp1];
char *RNameCharacter;
RNameCharacter = (char *) sqlite3_column_text(teststatement, 1);
NSString *RNameString = [[NSString alloc] initWithUTF8String:RNameCharacter];
[RNameArray addObject:RNameString];
[RIdArray addObject:RId];
}
}
[self getWalks];
}
-(void)getWalks
{
sqlite3 *walkNameDB;
if (sqlite3_open([[self databasePath] UTF8String], &walkNameDB) != SQLITE_OK) {
sqlite3_close(walkNameDB);
NSAssert(0, #"Failed to open Walk name database");
}
RegionWalksDictionary = [[NSMutableDictionary alloc] init];
for(regionId in RIdArray)
{
regionWalkArray = [[NSMutableArray alloc] init];
NSString *walkQuery = [[NSString alloc] initWithFormat:#"SELECT Wid,WName,SName from Walks,SubRegions WHERE Walks.Sid=SubRegions.Sid AND Rid = %d",[regionId integerValue] ];
sqlite3_stmt *walkstatement = nil;
// NSLog(#"%d",sqlite3_prepare_v2(walkNameDB,[walkQuery UTF8String], -1, &walkstatement, nil));
if (sqlite3_prepare_v2(walkNameDB,[walkQuery UTF8String], -1, &walkstatement, nil) == SQLITE_OK)
{
while( sqlite3_step(walkstatement) == SQLITE_ROW )
{
NSNumber *WId;
int temp1 = (int)sqlite3_column_int(walkstatement, 0);
WId = [[NSNumber alloc] initWithInt:temp1];
char *WNameCharacter;
WNameCharacter = (char *) sqlite3_column_text(walkstatement, 1);
NSString *WNameString = [[NSString alloc] initWithUTF8String:WNameCharacter];
char *SNameCharacter;
SNameCharacter = (char *) sqlite3_column_text(walkstatement, 2);
NSString *SNameString = [[NSString alloc] initWithUTF8String:SNameCharacter];
NSMutableDictionary *tempWalk = [[NSMutableDictionary alloc] init];
[tempWalk setObject:WId forKey:#"WalkId"];
[tempWalk setObject:WNameString forKey:#"WalkName"];
[tempWalk setObject:SNameString forKey:#"SubRegionName"];
[regionWalkArray addObject:tempWalk];
}
}
[RegionWalksDictionary setObject:regionWalkArray forKey:regionId];
// NSLog(#"arr%#",RegionWalksDictionary);
}
}
//*** Methods to get data from database ends here **************
Try this way...
for(id dict in RegionWalksDictionary){
NSLog(#"WalkId: %#",[[[RegionWalksDictionary objectForKey:dict]objectAtIndex:0]objectForKey:#"WalkId"] );
NSLog(#"WalkName: %#",[[[RegionWalksDictionary objectForKey:dict]objectAtIndex:0]objectForKey:#"WalkName"] );
NSLog(#"SubRegionName: %#",[[[RegionWalksDictionary objectForKey:dict]objectAtIndex:0]objectForKey:#"SubRegionName"] );
NSLog(#"----");
}
I have used as following (comment if this is not the structure or your data)
NSMutableDictionary *RegionWalksDictionary=[NSMutableDictionary new];
NSMutableArray *regionWalkArray=[NSMutableArray new];
NSMutableDictionary *tempWalk=[NSMutableDictionary new];
[tempWalk setObject:#"wk1" forKey:#"WalkId"];
[tempWalk setObject:#"wkName1" forKey:#"WalkName"];
[tempWalk setObject:#"srName1" forKey:#"SubRegionName"];
[regionWalkArray addObject:tempWalk];
[RegionWalksDictionary setObject:regionWalkArray forKey:#"1"];
[RegionWalksDictionary setObject:regionWalkArray forKey:#"2"];
[RegionWalksDictionary setObject:regionWalkArray forKey:#"3"];
NSLog(#"tempWalkd dict is %#",RegionWalksDictionary);
try this
NSString * walkName = [[parentDic objectForKey:[NSString stringWithFormat:#"%d",indexPath.row]] objectForKey:#"WalkName"];
NSString * SubregionName = [[parentDic objectForKey:[NSString stringWithFormat:#"%d",indexPath.row]] objectForKey:#"SubRegionName"];
It seems you have an NSDictionary with your 5 keys, and inside that you have an NSArray with a single element that is a NSDictionary. Although I might be wrong, try this:
NSDictionary *dictionaryForKey1 = [[myDictionary objectForKey:#"1"] objectAtIndex:0];
You can then use this:
NSString *walkName = [dictionaryForKey1 objectForKey:#"WalkName"];
AH! now I see it -- there are 5 arrays of length 1
NSArray *array1 = dict[#"1];
NSDictionary *details = array1[0];
//print each var
id WalkName = details[#"WalkName"];
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];
}
I'm looking for a nice clean routine for turning an NSArray containing NSNumbers (integers) into a nice English-readable string. For example, I want to change this:
[NSArray arrayWithObjects:[NSNumber numberWithInt:5],
[NSNumber numberWithInt:7],
[NSNumber numberWithInt:12],
[NSNumber numberWithInt:33], nil];
into this:
5, 7, 12 and 13.
Is there any nice way of doing this without hideous if statement logic? I'm sure it can be done with a regular expression, but is that possible in pre-iOS 4 code?
Thanks! :)
:-Joe
NSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:5],
[NSNumber numberWithInt:7],
[NSNumber numberWithInt:12],
[NSNumber numberWithInt:33], nil];
NSArray *first = [numbers subarrayWithRange:NSMakeRange(0, [numbers count]-1)];
NSString *joined = [[first componentsJoinedByString:#", "] stringByAppendingFormat:(([first count] > 0) ? #"and %#" : #"%#"), [numbers lastObject]];
Look mom, no ifs!
NSString *seps[] = {#" and ",#"",#", ",nil,nil,#", "}, *o = #".", *sep = o;
for ( NSNumber *n in [arr reverseObjectEnumerator] ) {
o = [NSString stringWithFormat:#"%#%#%#",n,sep = seps[[sep length]],o];
}
NSLog(#"out: %#",o);
output:
out: 5, 7, 12 and 33.
but why?
edit here is an understandable version with no "huge if/else construct"
NSString *out = #""; // no numbers = empty string
NSString *sep = #"."; // the separator first used is actually the ending "."
for ( NSNumber *n in [arr reverseObjectEnumerator] )
{
out = [NSString stringWithFormat:#"%#%#%#",n,sep,out];
if ( [sep isEqualToString:#"."] ) // was the separator the ending "." ?
{
sep = #" and "; // if so, put in the last separator " and "
} else {
sep = #", "; // otherwise, use separator ", "
}
}
This will output strings like
0 elements: "" (i.e. empty)
1 element: "33."
2 elements: "12 and 33."
3 elements: "7, 12 and 33."