I'm getting data from SQL server in following variables in one class:
#property(retain,nonatomic) NSString* trainingName;
#property(retain,nonatomic) NSNumber* trainingCount;
In other class,I want to append this value in NSMutableArray and finally make a dictonary.I'm doing this as following:
-(void)getTrainingDetails
{
MyTestSp_GetTrainingCountsList *objReturnTrainings = [MyTestSp_GetTrainingCounts findAll];
NSMutableArray *trainingNames = [[NSMutableArray alloc]init];
NSMutableArray *trainingCounts = [[NSMutableArray alloc]init];
NSMutableDictionary *dictTrainings = [[NSMutableDictionary alloc]init];
if ([objReturnTrainings length] > 0)
{
for (MyTestSp_GetTrainingCounts *obj in objReturnTrainings)
{
// get the values and assign to NSMutable array
trainingNames = trainingName;
trainingCounts = trainingCount;
//Make the dictionary.
}
}
}
Is this the correct way of doing and how can I put this in dictionary?
Please help.
You appear to be trying to set your array directly to your number / string (which you aren't actually getting out of obj so your code shouldn't compile...). You also don't need the arrays to create the dictionary. You can just do:
for (MyTestSp_GetTrainingCounts *obj in objReturnTrainings)
{
dictTrainings[obj.trainingName] = obj.trainingCount;
}
Related
I have an NSMutableArray of custom objects. Each contains an ID string that is unique, and each contains an downloadedDate property.
Objects could get added twice so I need to check the ID for duplicates, and if I find a duplicate I need to keep the one that has the newest date.
Currently I am doing the following to remove duplicates, but it doesn't take into account keeping the object with the newest date.
NSArray *originalArray = [NSArray arrayWithArray:mutableItems];
NSMutableArray *uniqueArray = [NSMutableArray array];
NSMutableSet *names = [NSMutableSet set];
for (ZSSObject *g in originalArray) {
NSString *destinationName = g.code;
if (![names containsObject:destinationName]) {
[uniqueArray addObject:g];
[names addObject:destinationName];
}
}
NSArray *uniqueObjects = uniqueArray;
Objects get created like this:
ZSSObject *obj = [ZSSObject alloc] init];
obj.code = #"12345";
obj.downloadedDate = [NSDate date];
Is there an easier way to do that I want than having a bunch of copies of my array and nested loops?
Using the suggestion to use an NSDictionary instead, I came up with this solution:
NSMutableDictionary *objDict = [[NSMutableDictionary alloc] init];
for (ZSSObject *g in mutableItems) {
ZSSObject *addedObj = objDict[g.code];
if (addedObj) {
// Compare dates
if ([addedObj respondsToSelector:#selector(dateDownloaded)]) {
if ([g.dateDownloaded compare:addedObj.dateDownloaded] == NSOrderedDescending) {
[objDict setObject:g forKey:g.code];
}
}
} else {
[objDict setObject:g forKey:g.code];
}
}
NSArray *uniqueObj = objDict.allValues;
How to convert an array into a dictionary in Objective-C language?
This is the array:
[{"1":"2"}, {"2":"3"}]
But I want :
{"1":"2", "2":"3"}
Please help me, I am a new iPhone developer.
I am assuming that you want to combine an array of dictionaries into a single dictionary.
NSArray *array = #[#{#"1":#"2"},#{#"2":#"3"}];
NSMutableDictionary *result = [[NSMutableDictionary alloc]init];
for (NSDictionary *dict in array)
{
[result addEntriesFromDictionary:dict];
}
/*
result = {
1 = 2;
2 = 3;
}
*/
Where did your data come from? The easiest way to "convert" the above is to simply create a single dictionary in the first place.
Otherwise:
NSMutableDictionary* newDict = [NSMutableDictionary dictionary];
for (NSDictionary* oldDict in sourceArray) {
[newDict addEntriesFromDictionary:oldDict];
}
I have a NSArray With NSMutableDictionary object inside this array like the following .What i want to get an object say at index:2 of this array and add that NSMutableDictionary object from the following array into other NSMutableDictionary already have say five elements at positions 6:
(
{
eventId = 2;
eventName = "Sweels ";
},
{
eventId = 1;
eventName = "Lakenge";
},
{
eventId = 23;
eventName = "Royta";
}
)
I am able to get the NSMutableDictionary object and and can extract the key and value and then can add but want to add whole object without extracting the key and values
{
eventId = 23;
eventName = "Royta";
}
You can initialize an NSMutableDictionary object with the keys and values contained in another given dictionary using this initializer:
- (instancetype)initWithDictionary:(NSDictionary *)otherDictionary
Example:
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] initWithDictionary:extractedDict];
If You do not want to create a new NSMutableDictionary Object and just need to add Key/Values to an existing Object then Use this Method:
- (void)setValuesForKeysWithDictionary:(NSDictionary *)keyedValues
Example:
[newDict setValuesForKeysWithDictionary:extractedDict];
If you want all the values as single object than you must do this-
NSMutableArray *myArray = [[NSMutableArray alloc] init];
[myArray addObjectsFromArray:[paramsDictionary allValues]];
NSLog(#"%#",[paramsDictionary allValues]);
We have an app that calls a SOAP web service and retrieves a long list of XML, which the app then parses into an NSArray of NSDictionary objects. The NSArray contains a list of Rental Apartment information, each of which is stored into an NSDictionary.
The entire list may contain 10 different types of Apartments (i.e. 2-room, 3-room), and we need to split the NSArray into smaller NSArrays based on Room-Type, which has the key "roomType" in the NSDictionary objects.
Currently our algorithm is
Use [NSArray valueForKeyPath:#"#distinctUnionofObjects.room-type"]
to obtain a list of unique room-type values.
Loop through the list of unique room-type values
For each unique room-type value, use NSPredicate to retrieve matching items from the Original list
Our code is below (renamed for clarity):
NSArray *arrOriginal = ... ...; // Contains the Parsed XML list
NSMutableArray *marrApartmentsByRoomType = [NSMutableArray arrayWithCapacity:10];
NSMutableArray *arrRoomTypes = [arrOriginal valueForKeyPath:#"distinctUnionOfObjects.roomType"];
for(NSString *strRoomType in arrRoomTypes) {
NSPredicate *predicateRoomType = [NSPredicate predicateWithFormat:#"roomType=%#", strRoomType];
NSArray *arrApartmentsThatMatchRoomType = [arrOriginal filteredArrayUsingPredicate:predicateRoomType]; // TAKES A LONG TIME EACH LOOP-ROUND
[marrApartmentsByRoomType addObject:arrApartmentsThatMatchRoomType];
}
However, step 3 is taking a long time as the original list may contain large amount (>100,000) of items. It seems that NSPredicate goes through the entire list for each key value. Is there a more efficient way of splitting a large NSArray into smaller NSArrays, based on NSDictionary keys?
If the order of your splited Arrays is not important, i have a solution for you:
NSArray *arrOriginal;
NSMutableDictionary *grouped = [[NSMutableDictionary alloc] initWithCapacity:arrOriginal.count];
for (NSDictionary *dict in arrOriginal) {
id key = [dict valueForKey:#"roomType"];
NSMutableArray *tmp = [grouped objectForKey:key];
if (tmp == nil) {
tmp = [[NSMutableArray alloc] init];
[grouped setObject:tmp forKey:key];
}
[tmp addObject:dict];
}
NSMutableArray *marrApartmentsByRoomType = [grouped allValues];
This is quite performant
- (NSDictionary *)groupObjectsInArray:(NSArray *)array byKey:(id <NSCopying> (^)(id item))keyForItemBlock
{
NSMutableDictionary *groupedItems = [NSMutableDictionary new];
for (id item in array) {
id <NSCopying> key = keyForItemBlock(item);
NSParameterAssert(key);
NSMutableArray *arrayForKey = groupedItems[key];
if (arrayForKey == nil) {
arrayForKey = [NSMutableArray new];
groupedItems[key] = arrayForKey;
}
[arrayForKey addObject:item];
}
return groupedItems;
}
Improving #Jonathan answer
Converting array to dictionary
Maintaining the same order as it was in original array
//only to a take unique keys. (key order should be maintained)
NSMutableArray *aMutableArray = [[NSMutableArray alloc]init];
NSMutableDictionary *dictFromArray = [NSMutableDictionary dictionary];
for (NSDictionary *eachDict in arrOriginal) {
//Collecting all unique key in order of initial array
NSString *eachKey = [eachDict objectForKey:#"roomType"];
if (![aMutableArray containsObject:eachKey]) {
[aMutableArray addObject:eachKey];
}
NSMutableArray *tmp = [grouped objectForKey:key];
tmp = [dictFromArray objectForKey:eachKey];
if (!tmp) {
tmp = [NSMutableArray array];
[dictFromArray setObject:tmp forKey:eachKey];
}
[tmp addObject:eachDict];
}
//NSLog(#"dictFromArray %#",dictFromArray);
//NSLog(#"Unique Keys :: %#",aMutableArray);
//Converting from dictionary to array again...
self.finalArray = [[NSMutableArray alloc]init];
for (NSString *uniqueKey in aMutableArray) {
NSDictionary *aUniqueKeyDict = #{#"groupKey":uniqueKey,#"featureValues":[dictFromArray objectForKey:uniqueKey]};
[self.finalArray addObject:aUniqueKeyDict];
}
Hope, It will help when client wants final array in same order as input array.
NSMutableDictionary *expense_ArrContents = [[NSMutableDictionary alloc]init];
for (int i = 1; i<=4; i++) {
NSMutableArray *current_row = [NSMutableArray arrayWithObjects:#"payer_id",#"Expense_Type_id",#"Category_Id",#"SubCategory_Id",nil];
[expense_ArrContents setObject:current_row forKey: [NSNumber numberWithInt:i]];
}
NSArray *newArray = [expense_ArrContents allKeysForObject:#"payer_id"];
NSLog(#"%#",[newArray description]);
i want to get the list of key values containing the particular object which is in the array of values stored in nsmutabledictionary for a particular key.
In the line where you get all the keys ([expense_ArrContents allKeysForObject:#"payer_id"];) you actually get keys for an object that is not in any of the array's items. This #"player_id" is different object than the #"player_id" you added in current_row. In fact, maybe all of your rows have different #"player_id" objects (except if the compiler has made some optimization - maybe it threats that same string literal as one object instead of creating new object for each iteration).
Try creating an NSString object for the #"player_id" which you add to the current_row and then get all the keys for that same object:
NSString* playerId = #"player_id";
for(){
NSMutableArray *current_row = [NSMutableArray arrayWithObjects: playerId,...];
...
}
NSArray *newArray = [expense_ArrContents allKeysForObject:playerId];
Your NSArray *newArray = [expense_ArrContents allKeysForObject:#"payer_id"]; will not return any value because in expense_ArrContents there is no such key(#"payer_id"), instead there are keys like 1,2,3 etc.What is your requirement?Want to see what all keys are there in expense_ArrContents just log
NSArray*keys=[expense_ArrContents allKeys];
Try this :
NSMutableArray *array_key=[[NSMutableArray alloc]init];
for (NSString *key in expense_ArrContents) {
if ([[expense_ArrContents objectForKey:key] containsObject:#"payer_id"]) {
[array_key addObject:key];
}
}