i used the Sort Descriptor to Sort the NSMutableArray By one & multiple Values,First i tried by to sort By Price,it sort in some other Order here is my code help me,
My
i create the Dictionary by below code and added to the NSMutableArray
for(int i=0;i<[priceArray count];i++)
{
cellDict=[[NSMutableDictionary alloc]init];
[cellDict setObject:nameArray[i] forKey:#"Name"];
[cellDict setObject:splPriceArray[i] forKey:#"Percentage"];
[cellDict setObject:priceArray[i] forKey:#"Price"];
[resultArray addObject:cellDict];
}
// To Sort in Ascending Order
NSSortDescriptor *sort =[[NSSortDescriptor alloc] initWithKey:#"Price" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObjects:sort, nil];
NSArray *sortedArray=[resultArray sortedArrayUsingDescriptors:descriptors];
NSLog(#"Result %# Sorted arr %#",resultArray, sortedArray);
And Output is:
Result (
{
Name = "Black Eyed Peas";
Percentage = 0;
Price = 80;
},
{
Name = "Black Gram";
Percentage = 0;
Price = 56;
},
{
Name = "Channa White";
Percentage = 0;
Price = 100;
},
{
Name = "Double Beans";
Percentage = 0;
Price = 95;
},
{
Name = "Gram Dall";
Percentage = 0;
Price = 100;
},
{
Name = "Green Moong Dal";
Percentage = 0;
Price = 150;
},
{
Name = "Ground Nut";
Percentage = 0;
Price = 140;
},
{
Name = "Moong Dal";
Percentage = 0;
Price = 75;
},
{
Name = "Orid Dal";
Percentage = 0;
Price = 100;
},
{
Name = "Toor Dal";
Percentage = 0;
Price = 150;
}
) Sorted arr (
{
Name = "Channa White";
Percentage = 0;
Price = 100;
},
{
Name = "Gram Dall";
Percentage = 0;
Price = 100;
},
{
Name = "Orid Dal";
Percentage = 0;
Price = 100;
},
{
Name = "Ground Nut";
Percentage = 0;
Price = 140;
},
{
Name = "Green Moong Dal";
Percentage = 0;
Price = 150;
},
{
Name = "Toor Dal";
Percentage = 0;
Price = 150;
},
{
Name = "Black Gram";
Percentage = 0;
Price = 56;
},
{
Name = "Moong Dal";
Percentage = 0;
Price = 75;
},
{
Name = "Black Eyed Peas";
Percentage = 0;
Price = 80;
},
{
Name = "Double Beans";
Percentage = 0;
Price = 95;
}
)
Here The Sorted Array Sorting in some other Order I want to sort this in Ascending order by price.
It's unclear what your test data looks like - but the following snippet works as expected
NSArray *priceArray = [NSArray arrayWithObjects:#(74),#(100),#(100),#(130), nil];
NSArray *nameArray = [NSArray arrayWithObjects:#"Yva",#"Hallo", #"Adam", #"Xavier", nil];
NSMutableArray *resultArray = [NSMutableArray new];
for(int i=0;i<[priceArray count];i++)
{
NSMutableDictionary *cellDict=[[NSMutableDictionary alloc]init];
[cellDict setObject:nameArray[i] forKey:#"Name"];
[cellDict setObject:priceArray[i] forKey:#"Percentage"];
[cellDict setObject:priceArray[i] forKey:#"Price"];
[resultArray addObject:cellDict];
}
// Sort by Name
//NSSortDescriptor *sort =[[NSSortDescriptor alloc] initWithKey:#"Price" ascending:YES];
// Sort by Name
NSSortDescriptor *sort =[[NSSortDescriptor alloc] initWithKey:#"Name" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
NSArray *descriptors = [NSArray arrayWithObjects:sort, nil];
NSArray *sortedArray=[resultArray sortedArrayUsingDescriptors:descriptors];
NSLog(#"Result %# Sorted arr %#",resultArray, sortedArray);
Result:
2015-07-11 12:54:54.358 ret[10480:162783] Result (
{
Name = Yva;
Percentage = 74;
Price = 74;
},
{
Name = Hallo;
Percentage = 100;
Price = 100;
},
{
Name = Adam;
Percentage = 100;
Price = 100;
},
{
Name = Xavier;
Percentage = 130;
Price = 130;
}
) Sorted arr (
{
Name = Adam;
Percentage = 100;
Price = 100;
},
{
Name = Hallo;
Percentage = 100;
Price = 100;
},
{
Name = Xavier;
Percentage = 130;
Price = 130;
},
{
Name = Yva;
Percentage = 74;
Price = 74;
}
)
Related
I know this may be a repeated question but I googled a lot but not able to find a suitable answer for me.
I have a NSMutableArray which has two NSDictionary with Keys and values which I need to populated on a UITableView. I have retrieved the value of the dictionary which I'm going populate using
NSMutableArray *mutArray = [responseArray valueForKey:#"Table"];
And I did like
NSMutableSet *names = [NSMutableSet set];
NSMutableArray *mutArray1 = [[NSMutableArray alloc] init];
for (id obj in mutArray) {
NSString *destinationName = [obj valueForKey:#"AssetClassName"];
if (![names containsObject:destinationName]) {
[mutArray1 addObject:destinationName];
[names addObject:destinationName];
}
}
Because the value AssetClassName is repeated. Now I have three values in mutArray1 which I need to show as UITableView section. Under AssetClassName I have Some data which determines the row in that section.
For retrieving that data I'm doing like
for (int i = 0; i < [mutArray1 count]; i++) {
NSMutableDictionary *a = [[NSMutableDictionary alloc] init];
NSMutableDictionary *b = [[NSMutableDictionary alloc] init];
for (NSDictionary *dict in mutArray) {
if ([[mutArray1 objectAtIndex:i] isEqualToString:[dict valueForKey:#"AssetClassName"]]) {
[a setObject:[dict objectForKey: #"SubAssetClassName"] forKey:#"Investment Categories"];
[a setObject:[dict valueForKey:#"Amount"] forKey:#"Amount (EUR)"];
[a setObject:[dict valueForKey:#"AllocationPercentage"] forKey:#"%"];
[a setObject:[dict valueForKey:#"ModelAllocationPercentage"] forKey:#"ModelAllocationPercentage"];
[b setObject:a forKey:[dict valueForKey:#"SubAssetClassName"]];
[mutdict setObject:b forKey:[dict valueForKey:#"AssetClassName"]];
}
}
}
mutdict is a NSMutableDictionary declared globally and is instantiate in viewdidLoad
mutdict = [[NSMutableDictionary alloc] init];
The values are inserted into mutdict as I needed. Each SubAssetClassName is added into AssetclassName accordingly.
But my problem is in my final dictionary i.e mutdict the values for SubAssetClassName is repeated.
Can anybody tell how to solve this.
My console
"AssetClassName" = {
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "HIGH YIELD BONDS";
"ModelAllocationPercentage" = 22;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "HIGH YIELD BONDS";
"ModelAllocationPercentage" = 22;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "HIGH YIELD BONDS";
"ModelAllocationPercentage" = 22;
};
};
"AssetClassName" = {
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "EMERGING MARKETS EQUITIES";
"ModelAllocationPercentage" = 10;
};
};
"AssetClassName" = {
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "STRUCTURED PRODUCTS";
"ModelAllocationPercentage" = 10;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "STRUCTURED PRODUCTS";
"ModelAllocationPercentage" = 10;
};
"SubAssetClass" = {
"%" = 0;
"Amount (EUR)" = 0;
"Investment Categories" = "STRUCTURED PRODUCTS";
"ModelAllocationPercentage" = 10;
};
};
}
Here I can see that all SubAssetClass values are same for each section but actually its not.
How can I solve this.
You need to create a new instance of your mutable dictionary inside the loop. Right now you create one instance and update it over and over. This results in one dictionary being added over and over.
Change you code as follows:
for (NSInteger i = 0; i < [mutArray1 count]; i++) {
NSMutableDictionary *b = [[NSMutableDictionary alloc] init];
for (NSDictionary *dict in mutArray) {
if ([[mutArray1 objectAtIndex:i] isEqualToString:[dict valueForKey:#"AssetClassName"]]) {
NSMutableDictionary *a = [[NSMutableDictionary alloc] init];
[a setObject:[dict objectForKey: #"SubAssetClassName"] forKey:#"Investment Categories"];
[a setObject:[dict valueForKey:#"Amount"] forKey:#"Amount (EUR)"];
[a setObject:[dict valueForKey:#"AllocationPercentage"] forKey:#"%"];
[a setObject:[dict valueForKey:#"ModelAllocationPercentage"] forKey:#"ModelAllocationPercentage"];
[b setObject:a forKey:[dict valueForKey:#"SubAssetClassName"]];
[mutdict setObject:b forKey:[dict valueForKey:#"AssetClassName"]];
}
}
}
Also, in most cases you should not be using valueForKey:. Use objectForKey: unless you have a clear and specific need to use key-value coding instead of simply getting an object from the dictionary for a given key.
Could someone help me how to predicate through the below data and retrieve the value for the key "Text". Initially i have dictionary with the below data
{
ArrayName1 = (
{
Target = "<null>";
Text = "Name1";
Value = 1;
},
{
Target = "<null>";
Text = "Name2";
Value = 2;
}
);
ArrayName2 = (
{
Target = "<null>";
Text = "Name3";
Value = 3;
},
{
Target = "<null>";
Text = "Name4";
Value = 4;
}
);
ArrayName3 = (
{
Target = "<null>";
Text = "Name5";
Value = 5;
},
{
Target = "<null>";
Text = "Name6";
Value = 6;
}
);
ArrayName4 = (
{
Target = "<null>";
Text = "somename";
Value = somevalue;
}
);
ArrayName4 = (
{
Target = "<null>";
Text = "somename";
Value = "somevalue";
}
);
}
I want the end result to be stored in the "resultarray" which should contain value of "Text" key by the search string from all the array and also want to store the corresponding value for the "Value" key in the same array.
Thanks,
Pradeep
#Dev.RK #Cyph3r - Below are the methods i tried. #Dev.RK,#Cyph3r. I tried the below methods including compound predicate.
//Method 1
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ANY %K.%K CONTAINS[c] %#", #"Practice",#"Text",searchTextString];
searchArray = [[quickSearchDataDict allValues] filteredArrayUsingPredicate:predicate];
//Method 2
NSPredicate *predicateArray1 = [NSPredicate predicateWithFormat:#"(TEXT==%#)",searchTextString];
NSPredicate * predicateArray2 = [NSPredicate predicateWithFormat:#"SELF.%K.%K contains[c] %#",#"ArrayName2",#"Text",searchTextString];
NSPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:#[predicateArray1,predicateArray2]];
searchArray = [[quickSearchDataDict allValues] filteredArrayUsingPredicate:predicate];
Try this, hope this will solved your problem-
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
for (int i=0; i<5; i++) {
NSMutableArray *ary=[[NSMutableArray alloc]init];
for (int j=0; j<2; j++) {
NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
[dic setValue:[NSString stringWithFormat:#"none"] forKey:#"Target"];
[dic setValue:[NSString stringWithFormat:#"tst%d",j] forKey:#"Text"];
[dic setValue:[NSString stringWithFormat:#"%d",j+i] forKey:#"Value"];
[ary addObject:dic];
}
[dict setObject:ary forKey:[NSString stringWithFormat:#"ArrayName%d",i]];
}
NSArray *searchary=[dict valueForKey:[NSString stringWithFormat:#"%#",#"ArrayName0"]];
NSPredicate *pre0 = [NSPredicate predicateWithFormat:#"SELF.%K contains[cd] %#",#"Text", #"tst"];
NSArray *resultArray= [searchary filteredArrayUsingPredicate:pre0];
NSLog(#"%#",resultArray);
here is the log-
1. Text==tst0
(
{
Target = none;
Text = tst0;
Value = 0;
}
)
2. Text==tst
(
{
Target = none;
Text = tst0;
Value = 0;
},
{
Target = none;
Text = tst1;
Value = 1;
}
)
and this is complete data-
{
ArrayName0 = (
{
Target = none;
Text = tst0;
Value = 0;
},
{
Target = none;
Text = tst1;
Value = 1;
}
);
ArrayName1 = (
{
Target = none;
Text = tst0;
Value = 1;
},
{
Target = none;
Text = tst1;
Value = 2;
}
);
ArrayName2 = (
{
Target = none;
Text = tst0;
Value = 2;
},
{
Target = none;
Text = tst1;
Value = 3;
}
);
ArrayName3 = (
{
Target = none;
Text = tst0;
Value = 3;
},
{
Target = none;
Text = tst1;
Value = 4;
}
);
ArrayName4 = (
{
Target = none;
Text = tst0;
Value = 4;
},
{
Target = none;
Text = tst1;
Value = 5;
}
);
}
I am storing those three datas in to one, if user likes to sort the by the price then, everything should be in order. Please help me to show it like that.
imgArr =[[NSArray alloc]init];
nameArr=[[NSArray alloc]init];
priceArr=[[NSArray alloc]init];
Json script that I've used like this.
{
image = "";
name = Blue;
"option_value_id" = 40;
price = 3;
"price_prefix" = "+";
"product_option_value_id" = 3;
quantity = 300;
subtract = 0;
weight = 3;
"weight_prefix" = "+";
},
{
image = "";
name = Green;
"option_value_id" = 41;
price = 1;
"price_prefix" = "+";
"product_option_value_id" = 1;
quantity = 100;
subtract = 0;
weight = 1;
"weight_prefix" = "+";
},
{
image = "";
name = Yellow;
"option_value_id" = 42;
price = 2;
"price_prefix" = "+";
"product_option_value_id" = 2;
quantity = 200;
subtract = 1;
weight = 2;
"weight_prefix" = "+";
}
Store all these dictionaries in one array and sort this array by any field-
-(NSArray *)sortArrayByPrice:(NSArray *)originalArray{
NSSortDescriptor *sortByPrice = [NSSortDescriptor sortDescriptorWithKey:#"price" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByPrice];
NSArray *sortedArray = [originalArray sortedArrayUsingDescriptors:sortDescriptors];
return sortedArray;
}
I'm a Begginer in Objective-C coding and I need some help on NSPredicates.
I need to filter (by id_especie) an Array of Dictionaries that I've parsed from a Json file and retrieve the data to another array. Unfortunate all I got is a null array;
That's my Array of Dictionaries (id_especie mean species_id and id_raca mean breed_id) :
{
"id_especie" = 1;
"id_raca" = 1;
raca = Afghanhound;
},
{
"id_especie" = 1;
"id_raca" = 2;
raca = "Airedale Terrier";
},
{
"id_especie" = 1;
"id_raca" = 3;
raca = Akita;
},...,
{
"id_especie" = 2;
"id_raca" = 47;
raca = "N/I";
},
{
"id_especie" = 2;
"id_raca" = 48;
raca = Siames;
},
{
"id_especie" = 3;
"id_raca" = 49;
raca = Periquito;
},
{
"id_especie" = 4;
"id_raca" = 50;
raca = Cobra;
},
{
"id_especie" = 4;
"id_raca" = 51;
raca = Lagarto;
},
{
"id_especie" = 5;
"id_raca" = 52;
raca = "Furao";
},
{
"id_especie" = 5;
"id_raca" = 53;
raca = Hamster;
},
{
"id_especie" = 6;
"id_raca" = 54;
raca = Outros;
}
And this is my code:
.h
#property (nonatomic, strong) NSMutableArray *arrayBreedAndSpecies;
#property (nonatomic, strong) NSArray *filteredArray; //edited
.m
NSError *errorLoad = nil;
NSURL *jsonUrl = [[NSURL alloc]initWithString:#"http://marcosdegni.com.br/petsistema/teste/raca.php"];
NSString *jsonString = [NSString stringWithContentsOfURL:jsonUrl encoding:NSUTF8StringEncoding error:&errorLoad];
if (!errorLoad) {
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
self.arrayBreedAndSpecies = [[NSMutableArray alloc] initWithArray:jsonArray];
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%# = %#",#"id_especie", #"2"];
[self.filteredArray setArray: [self.arrayBreedAndSpecies filteredArrayUsingPredicate:predicate]];
NSLog(#"Filter: %#", self.filteredArray);
OK I've noticed a few errors with your NSPredicate code:
1) A dynamic key path in a predicate should be %K not %#.
2) To check if a number value is equal to another you need to use == not just =
Therefore the last section of code should be:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K == %i",#"id_especie", 2];
self.filteredArray = [NSArray arrayWithArray:[self.arrayBreedAndSpecies filteredArrayUsingPredicate:predicate]];
NSLog(#"Filter: %#", self.filteredArray);
I'm assuming here that the id_especie property is a number value. If it is a string value you could use the predicate: [NSPredicate predicateWithFormat:#"%K MATCHES[cd] %#", #"id_especie", #"2"];
Hope this helps
just a guess here, because there isn't a working code example here:
[self.filteredArray setArray: [self.arrayBreedAndSpecies filteredArrayUsingPredicate:predicate]];
if self.filteredArray is nil, that line will do nothing... I bet you really mean:
self.filteredArray = [self.arrayBreedAndSpecies filteredArrayUsingPredicate:predicate];
I have NSMutableArray data as below.
(
{
Id = "-1";
NameEn = Country;
},
{
Id = 14;
NameEn = Iran;
},
{
Id = 11;
NameEn = Jordan;
},
{
Id = 5;
NameEn = "United Arab Emirates";
},
{
Id = 4;
NameEn = "Suadi Arabia";
},
{
Id = 3;
NameEn = Kuwait;
},
{
Id = 10;
NameEn = Yemen;
},
{
Id = 6;
NameEn = Oman;
},
{
Id = 12;
NameEn = Syria;
},
{
Id = 7;
NameEn = Qatar;
},
{
Id = 13;
NameEn = Lebanon;
},
{
Id = 1;
NameEn = Egypt;
},
{
Id = 8;
NameEn = "Bahrain Kingdom";
}
)
I want to find the location where Id=5.
Any idea how can I do?
I tried with below.
NSString *myCountry = [[NSUserDefaults standardUserDefaults] valueForKey:#"mCountryId"];
NSUInteger indexOfTheObject = [feedsCountry indexOfObject: myCountry];
NSLog(#"indexOfTheObject===%i==%#", indexOfTheObject, myCountry);
if (NSNotFound == indexOfTheObject) {
NSLog(#"not found...");
}
But I get output as not found... for mCountryId as 5.
Use an NSDictionary instead, and key your entries by Id; e.g.:
NSMutableDictionary* dictionary = [NSMutableDictionary new];
[dictionary setObject:#"Egypt" forKey:#"1"];
// (etc...)
EDIT: If you already have an array and can not change that, use a for loop like this:
for(NSDictionary* entry in givenArray){
NSString* key = [entry objectForKey:#"Id"];
NSString* value = [entry objectForKey:#"NameEn"];
[dictionary setObject:value forKey:key];
}
NSPredicate * filter = [NSPredicate predicateWithFormat:#"Id = 5"];
NSArray * filtered = [array filteredArrayUsingPredicate:filter];
The first object in filtered is the dictionary with Id = 5