i have a NSDictionary like:
{
"2017-05-02" = (
{
"always_valid" = 0;
date = "2017-05-02";
from = "12:00";
to = "13:00";
},
{
"always_valid" = 0;
date = "2017-05-02";
from = "12:00";
to = "12:00";
},
{
"always_valid" = 0;
date = "2017-05-02";
from = "14:00";
"hourly_rate" = 12;
to = "15:00";
}
);
"2017-05-03" = (
{
"always_valid" = 0;
date = "2017-05-03";
from = "12:00";
to = "13:00";
}
);
"2017-05-18" = (
{
"always_valid" = 1;
date = "2017-05-18";
from = "12:00";
to = "12:00";
}
);
}
i'm trying to apply
NSPredicate *filter = [NSPredicate predicateWithFormat:#"always_valid = \"1\""];
NSArray *alwaysvalid = [[dic allValues] filteredArrayUsingPredicate:filter];
it use to work when i had structure something like
array > dictionary
but now it's like
array > array > dictionary
by doing [dic allValues] for array.
any help what should i apply to keep it fast.
What you need to do is need enumerate your dictionary and create new filtered Dictionary.
NSMutableDictionary *filterDic = [[NSMutableDictionary alloc] init];
NSPredicate *filter = [NSPredicate predicateWithFormat:#"always_valid = 1"];
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSArray* obj, BOOL *stop) {
NSArray *filterArray = [obj filteredArrayUsingPredicate:filter];
if (filterArray.count > 0) {
filterDic[key] = filterArray;
}
}];
Try this :
NSArray *array = [NSArray arrayWithObject:dict]; // you can also do same for Name key...
NSArray *alwaysvalid = [array filteredArrayUsingPredicate:filter];
Related
Hi This is what am getting from server
{
1 = {
"display_name" = "One";
id = 1;
};
2 = {
"display_name" = "Two";
id = 2;
};
13 = {
"display_name" = "abc";
id = 13;
};
15 = {
"display_name" = "aaa";
id = 15;
};
4 = {
"display_name" = "ffd";
id = 4;
};
3 = {
"display_name" = "abdfdfc";
id = 3;
};
5 = {
"display_name" = "aasdfsdfa";
id = 5;
};
}
i need to sort this based on "id" this is what am looking as output
Expecting output
{
1 = {
"display_name" = "One";
id = 1;
};
2 = {
"display_name" = "Two";
id = 2;
};
3 = {
"display_name" = "abdfdfc";
id = 3;
};
4 = {
"display_name" = "ffd";
id = 4;
};
5 = {
"display_name" = "aasdfsdfa";
id = 5;
};
13 = {
"display_name" = "abc";
id = 13;
};
15 = {
"display_name" = "aaa";
id = 15;
};
}
This code i have tried and its not working
//vehiclesDictionary real dictionary
NSMutableArray *sortedKeys=[[NSMutableArray alloc]init];
for(NSString *item in [vehiclesDictionary allKeys]){
[sortedKeys addObject:[NSNumber numberWithInt:[item intValue]]];
}
NSArray *sortedKeysArray = [sortedKeys sortedArrayUsingSelector: #selector(compare:)];
NSLog(#"%#",sortedKeysArray);
NSMutableDictionary *sortedValues = [[NSMutableDictionary alloc] init];
for (NSString *key in sortedKeysArray) {
[sortedValues setValue:[vehiclesDictionary valueForKey:[NSString stringWithFormat:#"%#",key]] forKey:key];
}
NSLog(#"%#",sortedValues);
Pls help me
You cannot sort an NSDictionary, it is an unsorted collection type. You will need to store your keys in an array and sort this and use it to access the NSDictionary in order.
Based on your code above, it could be modified as follows, e.g.
NSDictionary *dict = [NSDictionary dictionary];
NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector:#selector(compare:)];
for (NSString *key in sortedKeys) {
NSLog(#"%#", [d objectForKey:key]);
// Do something with the object here
}
Here you can pass around the sortedKeys array with the NSDictionary, and use the sortedKeys array for in-order access to your NSDictionary.
A more concise approach to get the array, but with the same outcome as above, would be using:
NSDictionary -keysSortedByValueUsingComparator as shown here.
As others have mentioned, NSDictionaries cannot be sorted. However, you could do something like this:
-(NSArray *)sortedKeysFromDictionary:(NSDictionary *)dictionary ascending:(BOOL)ascending
{
/* get all keys from dictionary */
NSArray *allKeys = [dictionary allKeys];
NSString *key = #"id"; // using "id" as key here
/* sort keys */
NSSortDescriptor *dateDescriptor = [NSSortDescriptor sortDescriptorWithKey:key ascending:ascending];
return [NSArray arrayWithArray:[allKeys sortedArrayUsingDescriptors:#[dateDescriptor]]];
}
This will take all the keys from your dictionary, sort them in ascending or descending order as you desire and return that as an NSArray. This array can then be used to access the original dictionary. A sample implementation would look something like this:
for (NSString *key in [self sortedKeysFromDictionary:sampleDic ascending:NO])
{
/* get value from current key */
NSDictionary *currentDic = [sampleDic objectForKey:key];
}
in my project i applied the following code
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
diagnosedictforname = [[[dict6 objectForKey:#"diagnoses"]objectAtIndex:0]objectForKey:#"Diagnoses"];
NSLog(#" for ref id =%# ,name of diagnose=%# data is= %#",refidstr,diagnosedictforname ,diagnosisdict);
and the output in console is comes out as in the form
str : {
diagnoses = (
{
Diagnoses = {
"diagnosis_name" = "TRANSIENT ISCHEMIA";
};
DiagnosesHospitals = {
"charge_amt" = "1300.00";
discharges = "11200.00";
"hospital_id" = 3341;
id = 163080;
"medicare_amt" = "100.00";
"total_amt" = "1100.00";
};
}
);
response = 200;
}
ref id =3341 ,name of diagnose={
"diagnosis_name" = "TRANSIENT ISCHEMIA";
} data is= {
"charge_amt" = "1300.00";
discharges = "11200.00";
"hospital_id" = 3341;
id = 163080;
"medicare_amt" = "100.00";
"total_amt" = "1100.00";
}
now i just want to embed the values of both the Dictionaries into one dictionary
someone please help me to sort out this issue.
Make a mutable copy of the first dictionary:
NSMutableDictionary * mutDic = [dic1 mutableCopy];
and then:
[mutDic addEntriesFromDictionary:dic2];
Try this code:
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
NSMutableDictionary *diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
NSDictionary *diagnosedictforname = [[[dict6 objectForKey:#"diagnoses"]objectAtIndex:0]objectForKey:#"Diagnoses"];
NSArray *keys = [diagnosedictforname allKeys];
for (int i =0; i < keys.count; i++) {
NSString *key = [keys objectAtIndex:i];
[diagnosisdict setValue:[diagnosedictforname valueForKey:key] forKey:key];
}
NSLog(#"your dic -> %#", diagnosisdict);
I need to convert an NSMutableArray to an NSArray from JSON. I loaded the JSON and put it in an NSMutableArray.
NSMutableArray *banner = [[NSMutableArray alloc] init];
banner = [responseObject objectForKey:#"banner"];
This is test for loop:
for(int i = 0; i < [slider count]; i++) {
NSLog(#"%#", [[banner objectAtIndex:i] objectForKey:#"resim"]); }
This is log from the JSON:
(
{
id = 1;
resim = "http://localhost/sample_Files/banner_api/1.jpg";
},
{
id = 2;
resim = "http://localhost/sample_Files/banner_api/2.jpg";
},
{
id = 3;
resim = "http://localhost/sample_Files/banner_api/3.jpg";
}
)
I want to set all of this to be like the below NSArray:
NSArray *allImages = #[#"http://localhost/sample_Files/banner_api/1.jpg",#"http://localhost/sample_Files/banner_api/2.jpg",#"http://localhost/sample_Files/banner_api/3.jpg"];
How can I do this?
NSMutableArray * muArr = [NSMutableArray new];
for(NSDictionary * dict in yourMuArr) {
[muArr addObject:dict[#"resim"]];
}
NSArray * allImages = [NSArray arrayWithArray:muArr];
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 a NSArray of NSDictionary objects:
[
{
id = 1;
fromDate = 2014-04-03;
toDate = 2014-04-05;
date = 0000-00-00;
title = title 1
},
{
id = 1;
fromDate = 0000-00-00;
toDate = 0000-00-00;
date = 2014-04-03
title = title 1
},
{
id = 1;
fromDate = 0000-00-00;
toDate = 0000-00-00;
date = 2014-04-04;
title = title 1
},
{
id = 2;
fromDate = 0000-00-00;
toDate = 0000-00-00;
date = 2014-05-10;
title = title 2
},
{
id = 2;
fromDate = 0000-00-00;
toDate = 0000-00-00;
date = 2014-05-11;
title = title 2
}
]
I would like to merge dictionaries with same id value into one dictionary combining all date, fromDate and toDate keys, obtaining an array like this, that ignores zero values:
[
{
id = 1,
combinedDates = 2014-04-03, 2014-04-05, 2014-04-03, 2014-04-04;
title = title 1
},
{
id = 2,
combinedDates = 2014-05-10, 2014-05-11;
title = title 2
}
]
Can someone point me to the right direction?
I don't know of any way to do this other than basic brute force:
-(NSArray*)combinedArray:(NSArray*)array
{
NSMutableArray* combined = [NSMutableArray new];
// Iterate over each unique id value
for(id key in [NSSet setWithArray:[array valueForKeyPath:#"id"]])
{
// skip missing keys
if([key isKindOfClass:[NSNull class]])
continue;
// Sub array with only id = key
NSArray* filtered = [array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDictionary* evaluatedObject, NSDictionary *bindings) {
return [evaluatedObject valueForKey:#"date"] && [[evaluatedObject valueForKey:#"id"] isEqual:key];
}]];
// Grab the dates
NSArray* dates = [filtered valueForKeyPath:#"date"];
// add the new dictionary
[combined addObject:#{ #"id":key, #"combinedDates":dates }];
}
return array;
}
// Group By id
-(NSMutableDictionary*)combinedArray:(NSArray*)array
{
NSMutableArray *categories = [[NSMutableArray alloc] init];
for (NSDictionary *data in array) {
NSString *category = [data valueForKey:#"id"];
if (![categories containsObject:category]) {
[categories addObject:category];
}
}
NSMutableDictionary *categoryData = [[NSMutableDictionary alloc]init];
for (NSString *strCat in categories) {
NSMutableArray *catArray = [[NSMutableArray alloc]init];
for (NSDictionary *data in array) {
NSString *category = [data valueForKey:#"id"];
if ([category isEqualToString:strCat]) {
[catArray addObject:data];
}
}
[categoryData setObject:catArray forKey:strCat];
}
return categoryData;
}