I have following array,I have one array with multiple dictionaries,I need to get that dictionaries for same prod_type and create another array with unique key
nsarray
{
{
prod_type=abc;
fund=100;
};
{
prod_type=abc;
fund=100;
};
{
prod_type=abc;
fund=100;
};
{
prod_type=pqr;
fund=100;
};
{
prod_type=pqr;
fund=100;
};
{
prod_type=xyz;
fund=100;
};
{
prod_type=xyz;
fund=100;
};
I need following array format from above array
nsarray=
{
abc=
{
{
prod_type=abc;
fund=100;
};
{
prod_type=abc;
fund=100;
};
{
prod_type=abc;
fund=100;
};
}
pqr=
{
{
prod_type=pqr;
fund=100;
};
{
prod_type=pqr;
fund=100;
};
}
xyz=
{
{
prod_type=xyz;
fund=100;
};
{
prod_type=xyz;
fund=100;
};
}
}
Use NSPredicate to get desirable result.
NSString *selectedCategory=#"abc";
//filter array by category using predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"prod_type == %#", selectedCategory];
NSArray *filteredArray = [yourAry filteredArrayUsingPredicate:predicate];
NSDictionary *abcDic = [NSDictionary dictionaryWithObject:filteredArray forKey:#"abc"];
[yourNewAry addObject:abcDic];
You can repeat it for other
Here a nice explanation of it predicates
Use this code if you want a fully automated solution (without having to re-specify each prod_type):
NSMutableArray *keys = [originalArray mutableArrayValueForKey:#"prod_type"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:keys];
NSArray *uniqueKeys = orderedSet.array;
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
for(NSString *key in uniqueKeys){
NSPredicate *keyPredicate = [NSPredicate predicateWithFormat:#"prod_type = %#",key];
NSDictionary *keyDictionary = [NSDictionary dictionaryWithObject:[originalArray filteredArrayUsingPredicate:keyPredicate] forKey:key];
[resultArray addObject:keyDictionary];
}
NSLog(#"%#",resultArray);
try like this,
NSMutableDictionary *resultdict = [[NSMutableDictionary alloc]init];
NSMutableArray *keysArray =[array mutableArrayValueForKey:#"prod_type"];//here you'l get all the prod_type values in an array
for(int i=0;i<[keysArray count];i++){
NSPredicate *resultPredicate=[NSPredicate predicateWithFormat:#"prod_type CONTAINS %#",[keysArray objectAtIndex:i]];
NSArray* searchResults=[array filteredArrayUsingPredicate:resultPredicate];
[resultdict setObject:searchResults forKey:[keysArray objectAtIndex:i]];
}
NSLog(#"%#",resultdict);
EX:-
NSMutableArray *array =[[NSMutableArray alloc]init];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithObjects:#[#"abc",#"100"] forKeys:#[#"name",#"value"]];
NSMutableDictionary *dict1 = [[NSMutableDictionary alloc]initWithObjects:#[#"pqr",#"100"] forKeys:#[#"name",#"value"]];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]initWithObjects:#[#"pqr",#"100"] forKeys:#[#"name",#"value"]];
[array addObject:dict];
[array addObject:dict1];
[array addObject:dict2];
NSLog(#"%#",array);
(
{
name = abc;
value = 100;
},
{
name = pqr;
value = 100;
},
{
name = pqr;
value = 100;
}
)
NSMutableDictionary *resultdict = [[NSMutableDictionary alloc]init];
NSMutableArray *keysArray =[array mutableArrayValueForKey:#"name"];
for(int i=0;i<[keysArray count];i++){
NSPredicate *resultPredicate=[NSPredicate predicateWithFormat:#"name CONTAINS %#",[keysArray objectAtIndex:i]];
NSArray* searchResults=[array filteredArrayUsingPredicate:resultPredicate];
[resultdict setObject:searchResults forKey:[keysArray objectAtIndex:i]];
}
NSLog(#"%#",resultdict);
{
abc = (
{
name = abc;
value = 100;
}
);
pqr = (
{
name = pqr;
value = 100;
},
{
name = pqr;
value = 100;
}
);
}
Related
i'm working on one objective C application where i'm taking JSON data and i need to insert this data(date) inside Dictionary fillDefaultColors. My fillDefaultColors should be in format like this:
self.fillDefaultColors = #{ #"2017/06/18":greenColor,
#"2017/06/19":orangeColor,
#"2017/06/20":greenColor,
...
};
but when i print in console log they are each in separate row and in application i can see colour just for last item from JSON
2017-06-19 15:30:12.310 CalendarTest[1905:364525] {
"2017/06/20" = "greenColor";
}
2017-06-19 15:30:12.311 CalendarTest[1905:364525] {
"2017/06/18" = "orangeColor";
}
So in application i see background for last date in console 2017/06/18
Here is my code
NSError *error = nil;
NSURL *url = [NSURL URLWithString: #"http://..."];
NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
if(!error)
{
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
NSMutableArray *array= [json objectForKey:#"horses"];
for(int i=0; i< array.count; i++)
{
NSDictionary *horsedata = [array objectAtIndex:i];
NSString *date = [horsedata objectForKey:#"date"];
NSNumber *averagetemp = [horsedata objectForKey:#"averagetemperature"];
if([averagetemp isEqual:#(28)]) {tempColor = greenColor;} else {
tempColor = orangeColor;
}
self.fillDefaultColors = #{date: tempColor};
NSLog(#"%#", _fillDefaultColors);
}
}
JSON: {"horses":[{"id":1,"name":"Horse","date":"2017/06/17","averagetemperature":28},{"id":1,"name":"Horse","date":"2017/06/18","averagetemperature":25}]}
Thanks
it s because you are allocating a new dictionary in each iteration:
self.fillDefaultColors = #{date: tempColor};
you need to append instead:
NSMutableArray *array= [json objectForKey:#"horses"];
self.fillDefaultColors = [[NSMutableDictionary alloc]init];
for(int i=0; i< array.count; i++)
{
NSDictionary *horsedata = [array objectAtIndex:i];
NSString *date = [horsedata objectForKey:#"date"];
NSNumber *averagetemp = [horsedata objectForKey:#"averagetemperature"];
if([averagetemp isEqual:#(28)]) {tempColor = greenColor;} else {
tempColor = orangeColor;
}
[self.fillDefaultColors setObject:tempColor forKey:date];
NSLog(#"%#", _fillDefaultColors);
}
This is the same solution as in Hussein's answer but with Modern Objective-C Syntax – which has been introduced at least 5 years ago.
NSArray *horses = json[#"horses"];
self.fillDefaultColors = [[NSMutableDictionary alloc] init];
for (NSDictionary *horsedata in horses)
{
NSString *date = horsedata[#"date"];
NSNumber *averagetemp = horsedata[#"averagetemperature"];
self.fillDefaultColors[date] = (averagetemp.integerValue == 28) ? greenColor : orangeColor;
NSLog(#"%#", _fillDefaultColors);
}
I am replacing my obsolete ABAdressBook code with the current CNContact framework in Objective C. I could sort out most of it, except for the Home City part, so lets focus on that.
Currently I have this code:
-(NSArray *)getLandAddressesForContactIOS6:(ABRecordRef)recordRef {
ABMultiValueRef addresses = ABRecordCopyValue(recordRef, kABPersonAddressProperty);
NSMutableArray *formattedAddressesResponse = [NSMutableArray array];
for(CFIndex i = 0; i < ABMultiValueGetCount(addresses); i++) {
NSString *label = (__bridge NSString *)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(addresses, i));
NSDictionary *addressComponents = (__bridge NSDictionary*)ABMultiValueCopyValueAtIndex(addresses, i);
NSString *street = [addressComponents objectForKey:(NSString *)kABPersonAddressStreetKey];
NSString *city = [addressComponents objectForKey:(NSString *)kABPersonAddressCityKey];
NSString *formattedAddress = ABCreateStringWithAddressDictionary(addressComponents, YES);
NSMutableDictionary *currentAddressResponse = [NSMutableDictionary dictionaryWithObjectsAndKeys:
label, #"type",
label, #"label",
nil];
if (street != nil) {
[currentAddressResponse setObject:street forKey:#"street"];
}
if (city != nil) {
[currentAddressResponse setObject:city forKey:#"city"];
}
if (formattedAddress != nil) {
[currentAddressResponse setObject:formattedAddress forKey:#"formattedAddress"];
}
[formattedAddressesResponse addObject:currentAddressResponse];
}
return formattedAddressesResponse;
}
That code is deprecated for iOS 9+ so the closest I have got to get the home city with the new Contacts framework is:
-(NSArray *)getLandAddressesForContactIOS10:(CNContact*)recordRef {
NSArray <CNLabeledValue<CNPostalAddress *> *> *addresses = recordRef.postalAddresses;
NSMutableArray *formattedAdressResponse = [NSMutableArray array];
for(CFIndex i = 0; i < addresses.count; i++) {
CNLabeledValue *addressi = [addresses objectAtIndex:i];
//NSString *city = addressi.??????; //Stuck here, don't know what else to do
How can I extract the City name from a CNContact??
-(void )getLandAddressesForContactIOS10:(CNContact*)contact
{
for (CNLabeledValue<CNPostalAddress*>* labeledValue in contact.postalAddresses)
{
NSLog(#"%#",labeledValue.value.city);
NSLog(#"%#",labeledValue.value.street);
NSLog(#"%#",labeledValue.value.state);
NSLog(#"%#",labeledValue.value.postalCode);
NSLog(#"%#",labeledValue.value.ISOCountryCode);
}
}
NSArray *addresses = (NSArray*)[contact.postalAddresses valueForKey:#"value"];
if (!(addresses == nil) && addresses.count > 0)
{
for (CNLabeledValue<CNPostalAddress*>* labeledValue in contact.postalAddresses)
{
NSString *city = labeledValue.value.city;
NSLog(#"City = %#",city);
NSString *street = labeledValue.value.street;
NSLog(#"Street = %#",street);
NSString *state = labeledValue.value.state;
NSLog(#"State = %#",state);
NSString *postalCode = labeledValue.value.postalCode;
NSLog(#"PostalCode = %#",postalCode);
NSString *ISOCountryCode = labeledValue.value.ISOCountryCode;
NSLog(#"ISOCountryCode = %#",ISOCountryCode);
}
}
else
{
NSLog(#"No addresses for name = %#",strname);
}
NSArray *arrayBlockData = [data objectForKey:kData];
for (NSDictionary *dictTicket in arrayBlockData) {
NSString *blockId = [dictTicket objectForKey:#"block_id"];
[dictJson setObject:blockId forKey:#"block_id"];
[self.arrblockIds addObject:[dictTicket objectForKey:#"block_id"]];
}
[arrkeysAndValues addObject:dictJson];
NSLog(#"arrkeysAndValues %#",arrkeysAndValues);
reponse is :
arrKeysValues (
{
"block_id" = 624;
},
{
"block_id" = 624;
},
it should be :
arrKeysValues (
{
"block_id" = 623;
},
{
"block_id" = 624;
}
Your question isn't clear. But the code sample on how you put NSDictionary inside NSMutableArray is
NSMutableDictionary *dict = [NSMutableDictionary new];
[dict setValue:#623 forKey:#"block_id"];
NSMutableDictionary *dict2 = [NSMutableDictionary new];
[dict2 setValue:#624 forKey:#"block_id"];
NSMutableArray *newArray = [NSMutableArray new];
[newArray addObject:dict];
[newArray addObject:dict2];
NSLog(#"%#", newArray);
i have test array with objects structure - Group with (NSMutableArray)items, and i save group in YapDatabase
-(void)parseAndSaveJson:(id) json withCompleteBlock:(void(^)())completeBlock{
NSMutableArray *groupsArray = (NSMutableArray *)json;
if (groupsArray != nil) {
YapDatabaseConnection *connectnion = [[DatabaseManager sharedYapDatabase] newConnection];
[connectnion asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
for (int groupIndex = 0; groupIndex < [groupsArray count]; groupIndex ++) {
LocalGroupsExercise *localGroup = [[LocalGroupsExercise alloc] init];
localGroup.name = groupsArray[groupIndex][LOCAL_GROUPS_NAME];
localGroup.tagColor = groupsArray[groupIndex][LOCAL_GROUPS_TAG_COLOR];
localGroup.idGroup = [groupsArray[groupIndex][LOCAL_GROUPS_ID_GROUP] intValue];
if (groupsArray[groupIndex][LOCAL_GROUPS_EXERCISES] != nil) {
NSMutableArray *exerciseArray = (NSMutableArray *)groupsArray[groupIndex][LOCAL_GROUPS_EXERCISES];
for (int exerciseIndex = 0; exerciseIndex < [exerciseArray count]; exerciseIndex ++) {
LocalExercise *localExercise = [[LocalExercise alloc] init];
localExercise.name = exerciseArray[exerciseIndex][EXERCISE_NAME];
localExercise.exerciseId = [exerciseArray[exerciseIndex][LOCAL_EXERCISE_ID_EXERCISE] intValue];
localExercise.groupId = localGroup.idGroup;
localExercise.type = [exerciseArray[exerciseIndex][EXERCISE_TYPE] intValue];
localExercise.minWeight = [exerciseArray[exerciseIndex][EXERCISE_MIN_WEIGHT] floatValue];
localExercise.maxWeight = [exerciseArray[exerciseIndex][EXERCISE_MAX_WEIGHT] floatValue];
localExercise.minReps = [exerciseArray[exerciseIndex][EXERCISE_MIN_REPS] intValue];
localExercise.maxReps = [exerciseArray[exerciseIndex][EXERCISE_MAX_REPS] intValue];
localExercise.minTimer = [exerciseArray[exerciseIndex][EXERCISE_MIN_TIMER] intValue];
localExercise.maxTimer = [exerciseArray[exerciseIndex][EXERCISE_MAX_TIMER] intValue];
localExercise.timeRelax = [exerciseArray[exerciseIndex][EXERCISE_RELAX_TIME] intValue];
[localGroup.exercises addObject:localExercise];
}
}
[transaction setObject:localGroup forKey:[NSString stringWithFormat:#"%d", localGroup.idGroup] inCollection:LOCAL_GROUPS_CLASS_NAME];
}
YapDatabaseConnection *connectnion = [[DatabaseManager sharedYapDatabase] newConnection];
[connectnion readWithBlock:^(YapDatabaseReadTransaction *transaction) {
LocalGroupsExercise *group = [transaction objectForKey:#"2" inCollection:LOCAL_GROUPS_CLASS_NAME];
NSLog(#"%#", group.name);
NSLog(#"%#", group.tagColor);
NSLog(#"%#", group.exercises);
}];
} completionBlock:^{
completeBlock();
}];
}
}
+ (YapDatabaseView *)setupDatabaseViewForShowGroupsGyms{
YapDatabaseViewGrouping *grouping = [YapDatabaseViewGrouping withObjectBlock:^NSString *(YapDatabaseReadTransaction *transaction, NSString *collection, NSString *key, id object) {
if ([object isKindOfClass:[LocalGroupsExercise class]]) {
LocalGroupsExercise *groupExercise = (LocalGroupsExercise *)object;
return [NSString stringWithFormat:#"%#", groupExercise.name];
}
return nil;
}];
YapDatabaseViewSorting *sorting = [YapDatabaseViewSorting withObjectBlock:^NSComparisonResult(YapDatabaseReadTransaction *transaction, NSString *group, NSString *collection1, NSString *key1, LocalGroupsExercise *obj1, NSString *collection2, NSString *key2, LocalGroupsExercise *obj2) {
return [obj1.name compare:obj2.name options:NSNumericSearch range:NSMakeRange(0, obj1.name.length)];
}];
YapDatabaseView *databaseView = [[YapDatabaseView alloc] initWithGrouping:grouping sorting:sorting versionTag:#"0"];
return databaseView;
}
[[DatabaseManager sharedYapDatabase] registerExtension:self.databaseGroupView withName:LOCAL_GROUPS_CLASS_NAME];
[_connection beginLongLivedReadTransaction];
self.mappingsGroup = [[YapDatabaseViewMappings alloc] initWithGroupFilterBlock:^BOOL(NSString *group, YapDatabaseReadTransaction *transaction) {
return true;
} sortBlock:^NSComparisonResult(NSString *group1, NSString *group2, YapDatabaseReadTransaction *transaction) {
return [group1 compare:group2];
} view:LOCAL_GROUPS_CLASS_NAME];
[_connection readWithBlock:^(YapDatabaseReadTransaction *transaction) {
[self.mappingsGroup updateWithTransaction:transaction];
}];
The problem is that the group be NSMutabblArray and I want to see the objects in the table of the array, but [self.mappingsGroup numberOfItemsInSection:section] return only one items in group
You need to configure YapDatabase to use Mantle. By default, it will use NSCoding. (Which is why you're seeing an error about "encodeWithCoder:", as that method is part of NSCoding.)
Take a look at YapDatabase's wiki article entitled "Storing Objects", which talks about how it uses the serializer/deserializer blocks: https://github.com/yaptv/YapDatabase/wiki/Storing-Objects
Basically, when you alloc/init your YapDatabase instance, you'll want to pass a serializer & deserializer block that uses Mantle to perform the serialization/deserialization.
Also, see the various init methods that are available for YapDatabase: https://github.com/yaptv/YapDatabase/blob/master/YapDatabase/YapDatabase.h
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.