Concatenating values to the same key in an NSMutableDictionary - ios

I am getting data from my database and the data is being retrieved using a while loop.
success = [db executeQuery:#"SELECT * FROM apidataTwo;"];
while([success next]){
int first = [success intForColumn:#"id"];
NSString *id = [NSString stringWithFormat:#"%d",first];
[_tempArray addObject:id];
NSString *country_name = [success stringForColumn:#"country_name"];
[_tempArray addObject:country_name];
NSString *breezometer_description = [success stringForColumn:#"breezometer_description"];
[_tempArray addObject:breezometer_description];
NSString *country_description = [success stringForColumn:#"country_description"];
[_tempArray addObject:country_description];
NSString *dateString= [success stringForColumn:#"dateString"];
[_dateSectionArray addObject:dateString];
[_dataDictionary setObject:_tempArray forKey:dateString];
}
Suppose we get the same key in different iterations of the loop. When I pass the array to the NSMutableDictionary, the previous values will be replaced and lost.
And if I keep updating the NSMutableArray, then the values of a previous key will also be added to a different key.
So in situations like this when we want to concatenate the values to the same key, then what should be our approach.
The dictionary should look like this:
{
2016-10-05" = (
5,
"United States",
"Fair Air Quality",
"Good air quality"
);
"2016-10-06" = (
5,
"United States",
"Fair Air Quality",
"Good air quality"
);
}

Once you have figured out the key for this batch of data, try to retrieve an object from the dictionary for that key. If objectForKey: returns nil, then create a new mutable array. Then set that array as the dictionary's object for that key.
Every new batch of data is then added to the array, not to the dictionary. Here's a sketch of the structure:
while( /* processing data */){
// Collect this batch
NSArray * entry = ...;
// Figure out the dictionary key for the batch.
// (it doesn't have to be a string, this is just for example)
NSString * key = ...;
// Try to retrieve the object for that key
NSMutableArray * entries = _dataDictionary[key];
// If the result is `nil`, the key is not in the dictionary yet.
if( !entries ){
// Create a new mutable array
entries = [NSMutableArray array];
// Add that to the dictionary as the value for the given key
_dataDictionary[key] = entries;
}
// Now `entries` is a valid `NSMutableArray`, whether it already
// existed or was just created. Add this batch.
[entries addObject:entry];
// Move on to the next batch.
}

Related

How to create dynamic NSDictionary to store multiple URLs with multiple keys?

I want to store multiple urls with it's name , websitename and rssfeed url .
How can I store it in dictionary ?
Like ,
My key is , #"nameoffeed", #"websitename", #"urlfeedname" I want to store all in dictionary related to url .
Like user search 3 feed then name , websitename and urlfeed all are stored in NSDictionary ?
How can I do this ?
I am using this , but it stores only 1 value .
//newdevice1 is my nsmanageobject
NSArray *keys = [[[newDevice1 entity] attributesByName] allKeys];
NSDictionary *singledict = [newDevice1 dictionaryWithValuesForKeys:keys];
I need this type of result in dictionary.
{
nameoffeed = "cnn" ;
websitename = "www.cnn.com";
urlfeedname = "www.cnn.com/feed";
nameoffeed = "nytimes" ;
websitename = "www.nytimes.com";
urlfeedname = "www.nytimes.com/feed";
}
you can do by this way.
NSDictionary *dic = #{#"nameoffeed":#"cnn",#"websitename":#"www.cnn.com",#"urlfeedname":#"www.cnn.com/feed"};
NSDictionary *dic2 = #{#"nameoffeed":#"nytimes",#"websitename":#"www.nytimes.com",#"urlfeedname":#"www.nytimes.com/feed"};
NSArray *dicArray = #[dic,dic2];
My key is , #"nameoffeed", #"websitename", #"urlfeedname" I want to
store all in dictionary related to url . Like user search 3 feed then
name , websitename and urlfeed all are stored in NSDictionary ?
Based on this, I believe you want a dictionary of dictionaries, where each sub-dictionary is indexed by the name.
In your example, you are already creating the dictionary for an individual object using dictionaryWithValuesForKeys.
All you need to do is add each one to a dictionary by the url key.
First, you need a mutable dictionary to add items to...
NSMutableDictionary *byURL = [[NSMutableDictionary alloc] init];
Then, for each item, grab the "url" you will use as a key...
NSString *name = [newDevice1 valueForKey:#"nameoffeed"];
and add the values to the dictionary
if (name) {
NSArray *keys = [[[newDevice1 entity] attributesByName] allKeys];
byURL[name] = [newDevice1 dictionaryWithValuesForKeys:keys];
}
You can then do the same thing for each object, resulting in a dictionary where you can look up each object by url.
NSDictionary *d = byURL[#"cnn"];
will give you the dictionary containing all the key/value pairs for "cnn"
If you want to end up with an immutable dictionary that is to be used strictly for searching (after adding everything you want to add), you can create an immutable copy...
NSDictionary *objectsByURL = [byURL copy];
In Dictionary we can save or store the multiple key values.But it must be the Different key.The Key name must not be the same.If use store the same key name in dictionary,it shows you error or your app crashes.But you can have the same values in dictionary.You have to store the different key name with multiple same values.
You can save the save the set of dictionaries to array like below
NSDictionary *dictFirstSet = [[NSDictionary alloc]initWithObjectsAndKeys:#"cnn",#"nameoffeed",#"www.cnn.com",#"websitename",#"www.cnn.com/feed",#"urlfeedname",nil];
NSDictionary *dictSecondSet = [[NSDictionary alloc]initWithObjectsAndKeys:#"nytimes",#"nameoffeed",#"www.nytimes.com",#"websitename",#"www.nytimes.com/feed",#"urlfeedname",nil];
NSArray *arrayDict = [[NSArray alloc]initWithObjects:dictFirstSet,dictSecondSet,nil];
NSLog(#"The arrayDict is - %#",arrayDict);
The output is
The arrayDict is - (
{
nameoffeed = cnn;
urlfeedname = "www.cnn.com/feed";
websitename = "www.cnn.com";
},
{
nameoffeed = nytimes;
urlfeedname = "www.nytimes.com/feed";
websitename = "www.nytimes.com";
}
)

Insert array of value in particular attribute through core data

I have the json value like this ,
{
"product_color" = Black;
"product_description" = "The new Macbook air is ultraslim";
"product_id" = 1;
"product_large_image_url" = "https://www.gstatic.com/webp/gallery3/3_webp_ll.png";
"product_name" = "MacBook Air";
"product_price" = "$2500";
"product_size" = Small;
"product_stocks" = 50;
"product_thumb_image_url" = (
"https://www.gstatic.com/webp/gallery3/2_webp_ll.png",
......
......
);
}
and I want to insert the product_thumb_image_url array in a single attribute through core data,
what i have tried is:
+(void)insertingProduct: (int16_t) cId :(NSDictionary *)dictionary{
DataModel *dModel = [self dataModel];
Products *productDetails=[dModel createEntity:products];
productDetails.product_id=[[dictionary valueForKey:productid] integerValue];
productDetails.product_large_image_url = [dictionary valueForKey:productlargeImage];
productDetails.product_name=[dictionary valueForKey:productname];
productDetails.product_price=[[dictionary valueForKey:productPrice] integerValue];
productDetails.product_sizes=[dictionary valueForKey:productsizes];
productDetails.product_stocks=[[dictionary valueForKey:productstocks] integerValue];
productDetails.product_colors=[dictionary valueForKey:productcolors];
productDetails.product_description=[dictionary valueForKey:productdescription];
productDetails.product_thumb_image_url=[dictionary valueForKey:productThumbImage];
[dModel save];
}
but it shows that you can't insert an NSArray into an NSString, i am struggling to fix this ,
From your question, product_thumb_image_url is a String attribute in Core Data and [dictionary valueForKey:productThumbImage] returns an NSArray of URL strings from your incoming JSON.
So productDetails.product_thumb_image_url=[dictionary valueForKey:productThumbImage]; tries to store an array as a string, which obviously ins't possible.
You either need to store an Array in Core Data, which is done by making the attribute transformable, or you need to store only one image URL, which would be done by taking only the first item from the array (you should check that the array contains some items):
[[dictionary valueForKey:productThumbImage] firstObject]

iOS sort one array based on order of strings in another array

This is another very specific problem I am trying to solve.
I am pulling a list a twitter user accounts logged into the users settings application. This returns an array with the usernames in the correct order.
I then pass this array to this twitter API:
https://api.twitter.com/1.1/users/lookup.json
The returned array contain all the additional data I need for each user account logged in. The first array contains NSStrings (usernames), the returned array has been parsed to contain dictionaries that have a key and value for the username, name, and profile pic.
Problem now is that the order is completely different than the first array I passed.. This is expected behavior from Twitter, but it needs to be in the exact same order (I will be referencing the original index of the AccountStore which will match the first array, but not the new array of dictionaries).
How can I tell the new array to match the contained dictionaries to be the same order as the first array based on the username key?
I know this sounds confusing, so let me at least post the data to help.
Here is the first array output:
(
kbegeman,
indeedyes,
soiownabusiness,
iphonedev4me
)
Here is what the second array outputs:
(
{
image = "https://si0.twimg.com/profile_images/3518542448/3d2862eee546894a6b0600713a8de862_normal.jpeg";
name = "Kyle Begeman";
"screen_name" = kbegeman;
},
{
image = "https://si0.twimg.com/profile_images/481537542/image_normal.jpg";
name = "Jane Doe";
"screen_name" = iPhoneDev4Me;
},
{
image = "https://twimg0-a.akamaihd.net/profile_images/378800000139973355/787498ff5a80a5f45e234b79005f56b5_normal.jpeg";
name = "John Doe";
"screen_name" = indeedyes;
},
{
image = "https://si0.twimg.com/sticky/default_profile_images/default_profile_5_normal.png";
name = "Brad Pitt";
"screen_name" = soiownabusiness;
}
)
Due to the way Twitter returns the data, it is never the EXACT same order, so I have to check this every time I call these methods.
Any help would be great, would save my night. Thanks in advance!
You want the array of dictionaries be sorted by comparing screen_name value with your first array. Right? Also, the screen name may have different case than your username. Right?
I would use mapping dictionary:
Create dictionary from screen name to user dictionary:
NSArray *screenNames = [arrayOfUserDicts valueForKeyPath:#"screen_name.lowercaseString"];
NSDictionary *userDictsByScreenName = [NSDictionary dictionaryWithObjects:arrayOfUserDicts forKeys:screenNames];
Build final array by finding user dictionary for usernames in your array:
NSMutableArray *sortedUserDicts = [NSMutableArray arrayWithCapacity:arrayOfUsernames.count];
for (NSString *username in arrayOfUsernames) {
NSDictionary *userDict = [userDictsByScreenName objectForKey:username.lowercaseString];
[sortedUserDicts addObject:userDict];
}
First generate a mapping that maps the "screen_name" to the corresponding dictionary
in the second array:
NSDictionary *map = [NSDictionary dictionaryWithObjects:secondArray
forKeys:[secondArray valueForKey:#"screen_name"]];
Then you can create the sorted array with a single loop:
NSMutableArray *sorted = [NSMutableArray array];
for (NSString *name in firstArray) {
[sorted addObject:map[name]];
}
That sort order isn't something that could be easily replicated (i.e. it's not alpha, etc). Instead, you should just use that original NSArray as a guide to match data from the NSDictionary from Twitter. For example:
[twitterDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSInteger index = [yourLocalArray indexOfObject:obj];
if (index != NSNotFound) {
// You have a match, do something.
}
}];
lets name your arrays as firstArray and secondArray.
NSArray *sortedArray = [secondArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [#([firstArray indexOfObject:[obj1 objectForKey:#"name"]]) compare:#([firstArray indexOfObject:[obj2 objectForKey:#"name"]])];
}];

Add data from an array using its value for key to another Array

Hi i have two Arrays one being Parsed Data that has multiple entries at each cell (FolderName & ID) i want this data to be saved into another array like it is stored in the first array
FilteredData = [[NSMutableArray alloc]initWithArray:[ParsedData ValueForKey:#"FolderName"]];
SearchData = [[NSMutableArray alloc]initWithArray:FilteredData];
This is what i have been trying, The data Containing a dictionary at each entry is ParsedData, And the Array in which i have to copy these items is SearchData.
The Array (Parsed Data) Containing the dictionary looks like this
PARSED DATA (
{
CreatedBy = 1;
FolderName = Posteingang;
ID = 13000;
ParentID = 0;
},
{
CreatedBy = 1;
FolderName = Freigaben;
ID = 13001;
ParentID = 0;
},
From this Array I need to Get the FolderName And the ID and get them in the SearchData Array
SearchData (
Posteingang;
13000;
Freigaben;
13001;
)
I hope the question is clear now
check this one,
NSMutableArray *searchData = [NSMutableArray new];
for(NSDictionary *dict in ParsedDataArray){//here ParsedDataArray means PARSED DATA array name
NSDictionary *tempDict=[[NSDictionary alloc]initWithObjectsAndKeys:[dict ValueForKey:#"FolderName"],#"FolderName",[dict ValueForKey:#"ID"],#"ID" nil],
[searchData addObject:dict];
}
It seems like you misspelled the method name, it should be:
dictionaryWithObjectsAndKeys:
Notice the "s" after Object.
I want a dictionary inside an array which contains foldername and id
So you can get it using this:
NSMutableArray *searchData = [NSMutableArray new];
for(NSDictionary *dict in parsedDataArray){
NSDictionary *tempDict=#{#"FolderName":dict[#"FolderName"],
#"ID":dict[#"ID"]};
[searchData addObject:tempDict];
}
EDIT:
#[#"key:#"object"] is the new dictionary literal.
If you are using Xcode 4.3 or older need to do as:
NSDictionary *tempDict=#{#"FolderName":dict[#"FolderName"],
#"ID":dict[#"ID"]};
means,
NSDictionary *tempDict=[NSDictionary dictionaryWithObjectsAndKeys:[dict objectForKey:#"FolderName"], #"FolderName",[dict objectForKey:#"ID"],#"ID", nil];

How do I get properties out of NSDictionary?

I have a webservice that returns data to my client application in JSON. I am using TouchJson to then deserialize this data into a NSDictionary. Great. The dictionary contains a key, "results" and results contains an NSArray of objects.
These objects look like this when printed to log i.e
NSLog(#"Results Contents: %#",[resultsArray objectAtIndex:0 ]);
Outputs:
Results Contents: {
creationdate = "2011-06-29 22:03:24";
id = 1;
notes = "This is a test item";
title = "Test Item";
"users_id" = 1;
}
I can't determine what type this object is. How do I get the properties and values from this object?
Thanks!
To get the content of a NSDictionary you have to supply the key for the value that you want to retrieve. I.e:
NSString *notes = [[resultsArray objectAtIndex:0] valueForKey:#"notes"];
To test if object is an instance of class a, use one of these:
[yourObject isKindOfClass:[a class]]
[yourObject isMemberOfClass:[a class]]
To get object's class name you can use one of these:
const char* className = class_getName([yourObject class]);
NSString *className = NSStringFromClass([yourObject class]);
For an NSDictionary, you can use -allKeys to return an NSArray of dictionary keys. This will also let you know how many there are (by taking the count of the array). Once you know the type, you can call
[[resultsArray objectAtIndex:0] objectForKey:keyString];
where keyString is one of #"creationdate", #"notes", etc. However, if the class is not a subclass of NSObject, then instead use:
[[resultsArray objectAtIndex:0] valueForKey:keyString];
for example, you probably need to do this for keystring equal to #"id".

Resources