How to Add An array into Array index by index in iOS? - ios

i am newBie in iOS Development. i want to add my JSON Parsing Data Dictionary Array Key Value in to another array But it only Add My Last Array index in to New Array.
My Code like as
-(void)fetchedData:(NSData *)responsedata
{
if (responsedata.length > 0)
{
NSError* error;
self.json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
if ([[_json objectForKey:#"data"] isKindOfClass:[NSArray class]])
{
NSArray *arr = (NSArray *)[_json objectForKey:#"data"];
[self.imageArray addObjectsFromArray:arr];
[self.storeViewTable reloadData];
}
self.storeViewTable.hidden=FALSE;
}
NSMutableArray *imagearray=[[NSMutableArray alloc]init];
for (index=0; index <[self.imageArray count]; index ++)
{
for(NSDictionary *dict in self.imageArray )
{
imagearray = [dict valueForKey:#"demopage"];
self.imagesa = imagearray;
}
}
NSLog(#"Array Count %d",[self.imagesa count]);
NSLog(#"Another array Count %d",[self.imageArray count]);
}
Here self.imagearray is my main array that contain my all JSON Data but i want to Parse A new Data From old Data And add it in to self.imagesa array here For self-images Value for key is demo page and Self.imagearray count is Three(3) So i want all my Three Index value in to self.imagesa but it contain only Last index Value please Give me Solution For that.And my Webservices link is Here. link

your code should look like below.
id json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
if ([[json objectForKey:#"data"] isKindOfClass:[NSArray class]])
{
NSArray *arr = (NSArray *)[json objectForKey:#"data"];
[imageArray addObjectsFromArray:arr];
}
//do not alloc init if you have already alloc init array.
NSMutableArray *imagesa=[[NSMutableArray alloc]init];
for(NSDictionary *dict in imageArray )
{
[imagesa addObject:#{#"demopage":[dict valueForKey:#"demopage"]}];
}
NSLog(#"Array Count %lu",(unsigned long)[imagesa count]);
NSLog(#"Another array Count %lu",(unsigned long)[imageArray count]);
and i got below output
Array Count 3
Another array Count 3
NOTE
and if you want to add all demopage dictionary to imagesa array then replace your for loop
for(NSDictionary *dict in imageArray )
{
NSArray *arr = (NSArray *)[dict valueForKey:#"demopage"];
[imagesa addObjectsFromArray:arr];
}
and output is
Array Count 69
Another array Count 3

Related

Get only last vale of dictionary [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am new in iOS development and my problem is when i parse data than only last value is showing above value are not showing .Please solve my issue.
Array name city info get 3 value but when i want to display them it gives onle last value of array.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:WebData1 options:0 error:0];
NSArray *city_info = [json objectForKey:#"city_info"];
for(NSDictionary *dic in city_info) {
NSMutableArray *vlcc_service_name = [dic objectForKey:#"vlcc_service_name"];
Centers = [[NSMutableArray alloc]initWithObjects:vlcc_service_name, nil];
}
// NSLog(#"%#", vlcc_service_name);
NSLog(#"%#", Centers);
[_CenterTableView reloadData];
}
NSDictionaries are unordered,that there are not first or last element. In fact, the order of the keys are never guaranteed to be the same, even in the lifetime of a specific dictionary.
If you want any object, you can get one of the keys:
id key = [[json allKeys] objectAtIndex:0]; // ensure that your 'json' is not empty
id object = [json objectForKey:key];
Choice - 2
array you can get all objects
Centers = [NSMutableArray new]; // allocate the memory on outside the Loop
for(NSDictionary *dic in city_info) {
[Centers addObject: [dic objectForKey:#"vlcc_service_name"]];
}
NSLog(#"the last object=%#", [Centers lastObject]);
// else
NSLog(#"the last object=%#", [yourArray objectAtIndex:[Centers count] - 1]; );
Please try with this.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:WebData1 options:0 error:0];
NSArray *city_info = [json objectForKey:#"city_info"];
NSMutableArray *Centers = [[NSMutableArray alloc]init];
for(NSDictionary *dic in city_info) {
NSString *vlcc_service_name = [dic objectForKey:#"vlcc_service_name"];
/NSLog(#"%#", vlcc_service_name);
[Centers addObject: vlcc_service_name];
}
NSLog(#"%#", Centers);
[_CenterTableView reloadData];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:WebData1 options:0 error:0];
NSArray *city_info = [json objectForKey:#"city_info"];
NSMutableArray *Centers = [NSMutableArray array];
for(NSDictionary *dic in city_info) {
NSMutableArray *vlcc_service_name = [dic objectForKey:#"vlcc_service_name"];
[Centers addObjectsFromArray:vlcc_service_name];
}
// NSLog(#"%#", vlcc_service_name);
NSLog(#"%#", Centers);
[_CenterTableView reloadData];
}
You can do it without any for loop. Do like this:
NSMutableArray *Centers = [[NSMutableArray alloc]initwithArray:city_info];

How to get the no. of objects in JSON Data?

If i am saving my data in NSDictionary "dict"
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];
How can i know that how many objects i am having in seasons, i know how to save NSArray and it's count but it's not an array actually. and all question i saw on stackoverflow they all are using array object.
{ "seasons":{
"Season 0":{ },
"Season 1":{ }
}
NSDictionary has a count method:
NSInteger count = [dict[#"seasons"] count]; // Returns 2
Try This It will give the array of values / keys
[dict allValues]; or [dict allKeys]

Remove entries from NSMutableDictionary based on match on NSString value

After a network call to the Instagram API, I get back a responseDictionary NSDictionary delegate with the following Key/Value structure:
{
data = (
{
bio = "Los Angeles/Orange County Realtor\U00ae \n\U6d1b\U6749\U77f6\U623f\U5730\U4ea7\U7ecf\U7eaa\U4eba\nCall/Text/WhatsApp: (310) 717-1321\nEmail: Jxxxcom\nWeChat (\U5fae\U4fe1): xx";
"full_name" = "xx yy (\U7530\U4f73\U6dfc) Rx Realty";
id = 25354408;
"profile_picture" = "http://scontent-a.cdninstagram.com/hphotos-xpa1/outbound-distillery/t0.0-20/OBPTH/profiles/profile_xxx_75sq_1391378894.jpg";
username = jxxi;
website = "http://www.Jxghty.com";
},
The profile_picture key often has an NSString value that contains anonymousUser (for the users who didn't set any profile pictures).
I am looking to remove those entries from my responseDictionary as follows:
//Create mutable copy of IG responseDictionary
NSMutableDictionary *dictCleanAvatars = [responseDictionary mutableCopy];
NSLog(#"Log dictCleanAvatars after mutableCopy IG response: %#", dictCleanAvatars);
NSArray *keys = [dictCleanAvatars allKeys]; //get all the keys
NSUInteger k2 = [dictCleanAvatars count];
NSLog(#"k2 in dictCleanAvatars before cleanup is: %lu", (unsigned long)k2);
for (int i = 0; i<k2; i++)
{
if ([[dictCleanAvatars objectForKey:[keys objectAtIndex:i]] isKindOfClass:[NSString class]])
{
//if its an NSString - don't want an exception if its another type of object
NSLog(#"Yes, objectAtIndex:i us Kind ofClass NSString for i = %d", i);
if ([[dictCleanAvatars objectForKey:[keys objectAtIndex:i]] rangeOfString:#"anonymousUser"].location != NSNotFound)
{
NSLog(#"Yes, anonymousUser identified in objectAtIndex:i for i = %d", i);
//if object has the key word im looking for
[dictCleanAvatars removeObjectForKey:[keys objectAtIndex:i]]; //remove the key
NSLog(#"That's dictCleanAvatars after loop %d: %#", i, dictCleanAvatars);
}
}
}
But this doesn't work.
Would value feedback from more experience iOS developers.
If you're trying to build an array that includes everything from the data key's array, but omitting those dictionaries for which profile_picture contains the string "AnonymousUser", you can use NSPredicate:
NSArray *dataArray = responseDictionary[#"data"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"not (profile_picture contains 'AnonymousUser')"];
NSArray *filteredArray = [dataArray filteredArrayUsingPredicate:predicate];
Or you can use predicateWithBlock:
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(NSDictionary *evaluatedObject, NSDictionary *bindings) {
return [evaluatedObject[#"profile_picture"] rangeOfString:#"AnonymousUser"].location == NSNotFound;
}];
BTW, if you already have a mutable array, you can also remove entries from it using filterUsingPredicate, using the above predicates:
NSMutableArray *mutableDataArray = [responseDictionary[#"data"] mutableCopy];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"not (profile_picture contains 'AnonymousUser')"];
[mutableDataArray filterUsingPredicate:predicate];
If, on the other hand, you don't want to remove entire dictionaries from the array of dictionaries, but rather want to simply remove the occurrences of profile_picture for which "AnonymousUser" is present, you want to ensure that not only is the array mutable, but so are its constituent dictionaries.
The easiest way of doing this is to specify the NSJSONReadingMutableContainers option when parsing the JSON. Then you can just iterate through the NSMutableDictionary entries, removing the profile_picture entries with a profile_picture with "AnonymousUser" in them:
NSMutableDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSMutableArray *mutableDataArray = responseDictionary[#"data"];
for (NSMutableDictionary *dictionary in mutableDataArray) {
NSString *profilePicture = dictionary[#"profile_picture"];
if ([profilePicture rangeOfString:#"AnonymousUser"].location != NSNotFound) {
[dictionary removeObjectForKey:#"profile_picture"];
}
}
If, however, you can't specify the NSJSONReadingMutableContainers option when you parse the JSON and are stuck with a immutable collection, you need to make a mutable copy of it. Unfortunately, a simple mutableCopy of the array won't make the member dictionaries mutable themselves, but you can use a Core Foundation call to CFPropertyListCreateDeepCopy to make a mutable array with mutable entries, which you can then modify:
NSMutableArray *mutableDataArray = CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFArrayRef)responseDictionary[#"data"], kCFPropertyListMutableContainers));
Then you can use the above for loop, iterating through this array's dictionary entries, removing the offending profile_picture entries.
if [[dictCleanAvatars objectForKey:[keys objectAtIndex:i]] isEqualToString#"anonymousUser"] {
The problem is, suppose [dictCleanAvatars objectForKey:[keys objectAtIndex:i]] is not an NSString? You might want to check for that first.
If the only field you are looking at is profile_picture, I would go with a less generic approach which is much more readable and understandable
This code works for me
- (void)testExample
{
NSDictionary *dictionary = #{ #"data": #[ #{ #"bio": #"blah blah", #"profile_picture": #"some stuff anonymousUser other stuff" },
#{ #"bio": #"some other object", #"profile_picture": #"some other profile picture link" }] };
// dictionary is a mock of the data you provided
NSArray *data = [dictionary objectForKey:#"data"];
for (NSDictionary * avatarDict in data) {
NSMutableDictionary *mdict = [avatarDict mutableCopy];
id ppid = [mdict objectForKey:#"profile_picture"];
if ([ppid isKindOfClass:[NSString class]]) {
NSString *pp = (NSString *)ppid;
if ([pp rangeOfString:#"anonymousUser"].location != NSNotFound) {
[mdict removeObjectForKey:#"profile_picture"];
}
}
NSLog(#"altered dictionary: %#", mdict);
}
}
Output:
2014-08-13 10:53:36.727 test[11981:60b] altered dictionary: {
bio = "blah blah";
}
2014-08-13 10:53:36.728 test[11981:60b] altered dictionary: {
bio = "some other object";
"profile_picture" = "some other profile picture link";
}

How to get array of values from NSDictionary array

When I try to print array of json values in log, I get addresses instead of values. Here's how I coded.
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:jsonArray.count];
NSMutableArray *anotherTempArray = [NSMutableArray arrayWithCapacity:jsonArray.count];
NSDictionary *dict;
for(dict in jsonArray)
{
NSString *projectName = dict[#"Name"];
NSString *urlText = dict[#"Url"];
NSLog(#"Url text in array = %#", urlText);
NSString *attch = dict[#"attachmentes"];
NSLog(#"Attached url in array = %#", attch);
NSString *projID = dict[#"ProjectID"];
NSLog(#"Project ID in array = %#", projID);
SaveAttachment *saveAt = [[SaveAttachment alloc] initWithName:projectName withList:#"View" withAttachment:#"View"];
[tempArray addObject:saveAt];
SaveProjectId *saveProj = [[SaveProjectId alloc] initWithProjectId:projID];
saveProj.projectId = projID;
[anotherTempArray addObject:saveProj];
}
array = tempArray;
[self.tableViewProject reloadData];
NSLog(#"Array of project IDs === %#", anotherTempArray); //Get values (array of project ids here.
}
Replace
SaveProjectId *saveProj = [[SaveProjectId alloc] initWithProjectId:projID];
saveProj.projectId = projID;
[anotherTempArray addObject:saveProj];
with
[anotherTempArray addObject:projID];
This is because your anotherTempArray contains objects of SaveProjectId ie, everytime in for loop you are adding saveProj object not projID. Thats why your array showing SaveProjectId objects.
If you want to directly save them, then use the below modification
[anotherTempArray addObject:projID];
or you can use like(this is i would prefer)
NSLog(#"First project ID === %#", [anotherTempArray objectAtindex:0] projectId]);
You are storing SaveProjectId objects in the array, therefore when you print the content you see the address of those objects.
your "anotherTemoArray" is having objects of SaveProbectId so you have to pass object at index to SaveProjectId and then you can see the array information
When calling NSLog(#"Array of project IDs === %#", anotherTempArray); the -(NSString*)description method on each of the objects inside 'anotherTempArray' is being called.
In your case that means -(NSString*)description is being called on SaveProjectId objects. Override it to print out what you want... e.g.
-(NSString*)description {
return [NSString stringWithFormat:#"SaveProjectId: %#",self.projectId];
}

How to iterate multiple NSDictionary one of the key's value, and add them to a NSMutableArray?

I have an NSArray containing multiple NSDictionary fetching from the server, and i want to iterate every NSDictionary one of the key's value called "id" and then add them to a NSMutableArray. I used "for loop" to implement this function, but the results of the NSMutableArray log in Xcode debug area was very weird and incorrectly.
This is the code for iterate every NSDictionary in a NSArray.
//Get the dictionary that included item ids.
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
//Create the array add item id objects.
NSMutableArray *itemIds = [NSMutableArray array];
//Fetching item ids in dictionary array.
NSArray *itemIdsDictionary = dictionary[#"itemRefs"];
NSLog(#"%i", [itemIdsDictionary count]);//Have valid dictionary.
for(int i = 0; i < [itemIdsDictionary count]; i++)
{
NSString *aId = (itemIdsDictionary[i])[#"id"];
[itemIds addObject:aId];
NSLog(#"%#", itemIds);
NSLog(#"%#", aId);
}
the NSMutableArray log in Xcode degug area is:
2013-07-04 22:55:26.053 Readable[3222:c07] 5
2013-07-04 22:55:26.053 Readable[3222:c07] (
51d58c198e49d061db0011e3
)
2013-07-04 22:55:26.054 Readable[3222:c07] (
51d58c198e49d061db0011e3,
51d58c198e49d061db0011e4
)
2013-07-04 22:55:26.054 Readable[3222:c07] (
51d58c198e49d061db0011e3,
51d58c198e49d061db0011e4,
51d5745982d493d61500e706
)
2013-07-04 22:55:26.054 Readable[3222:c07] (
51d58c198e49d061db0011e3,
51d58c198e49d061db0011e4,
51d5745982d493d61500e706,
51d5745982d493d61500e707
)
2013-07-04 22:55:26.054 Readable[3222:c07] (
51d58c198e49d061db0011e3,
51d58c198e49d061db0011e4,
51d5745982d493d61500e706,
51d5745982d493d61500e707,
51d55fb04de3837bf3006e83
)
Really hope someone can help me solve this problem, and this is very important phase in my own app. Thanks!!!!!!
Try this -
for(int i = 0; i < [itemIdsDictionary count]; i++)
{
NSDictionary *dictionary = [itemIdsDictionary objectAtIndex:i];
[itemIds addObject:[dictionary objectForKey:#"id"]];
}
NSLog(#"itemIds : %#",itemIds);
Try
for (NSDictionary *dict in itemIdsDictionary)
[itemIds addObject:[dict valueForKey#"id"]];
It would also help if you gave the structure of your dictionary. What keys are returned from the web service? ect.
//Get the dictionary that included item ids.
NSDictionary *dictionary = [NSDictionary dictionary];
//Create the array to hold the ID's
NSMutableArray *itemIds = [NSMutableArray array];
//Fetching item ids in dictionary array.
NSArray *itemIdsDictionary = dictionary[#"itemRefs"];
[itemIdsDictionary enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL *stop) {
[itemIds addObject:[dict objectForKey:#"id"]];
}];
Here is an example of what I think you are tying to do.
If you want to make sure you only have one entry of an ID even if there are duplicates in your dictionary from the web service you can use a NSMutableSet to stop this. Below is the example of both.
//This is just an array to hold the dictionaries that you should get from the web service
NSMutableArray *arrayOfDictionariesFromWebService = [NSMutableArray array];
//Make some fake data for the example
for (int i = 0; i < 5; ++i)
{
//Make a dictionary with a value for the key id
NSDictionary *dictionary = #{#"id" : [NSString stringWithFormat:#"ID%d", i]};
//Add it to the array
[arrayOfDictionariesFromWebService addObject:dictionary];
}
//Add a duplicate item to show example of using a set
NSDictionary *duplicateObject = #{#"id" : #"ID0"};
[arrayOfDictionariesFromWebService addObject:duplicateObject];
//Create an array and a set to hold the ID's
NSMutableArray *itemIds = [NSMutableArray array];
NSMutableSet *setOfItemIds = [NSMutableSet set];
//Enumerate through the array of dictionaries to pull out the ID from the dictionary and add it to the array and set of IDs
[arrayOfDictionariesFromWebService enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL *stop) {
[itemIds addObject:[dict objectForKey:#"id"]];
[setOfItemIds addObject:[dict objectForKey:#"id"]];
}];
//If you want to sort your ID's you can sort it using sortedArrayUsingDescriptors
NSArray *sortedArrayOfItemIDs = [[setOfItemIds allObjects] sortedArrayUsingDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"description" ascending:YES]]];
//Log out the result
NSLog(#"Array of ID's \n%#", itemIds);
NSLog(#"Array of ID's from the set \n%#", [setOfItemIds allObjects]);
NSLog(#"Sorted array of ID's from the set \n%#", sortedArrayOfItemIDs);
The console should look like this.
2013-07-10 09:04:40.824 STC Companion[574:c07] Array of ID's
(
ID0,
ID1,
ID2,
ID3,
ID4,
ID0
)
2013-07-10 09:04:40.825 STC Companion[574:c07] Array of ID's from the set
(
ID2,
ID3,
ID0,
ID4,
ID1
}
2013-07-10 09:13:08.063 STC Companion[886:c07] Sorted array of ID's from the set
(
ID0,
ID1,
ID2,
ID3,
ID4
)

Resources