I want to remove object from array but I am getting this error. I found relative questions but not able to get.
please help me.
my code is
NSArray *tripsArray= [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSMutableArray *myTripsArray = [tripsArray mutableCopy];
for (NSDictionary *dict in myTripsArray){
if ([[dict valueForKey:#"state"] isEqualToString:#"undeployed"]){
int index = [myTripsArray indexOfObject:dict];
[myTripsArray removeObjectAtIndex:index];
}
}
This is due to the array which you are iterating, you are removing an object from the same array.
Change this line:
for (NSDictionary *dict in myTripsArray)
To this:
for (NSDictionary *dict in [myTripsArray copy])
Here I used the copy of the array to iterate and used the original one to mutate.
Try doing this:
NSArray *tripsArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSMutableArray *myTripsArray = [tripsArray mutableCopy];
for (NSDictionary *dict in [myTripsArray copy]){
if ([[dict valueForKey:#"state"] isEqualToString:#"undeployed"]){
int index = [myTripsArray indexOfObject:dict];
[myTripsArray removeObjectAtIndex:index];
}
}
// And now myTripsArray will be changed
You got the error because you tried to change an array in enumerating time. You should make copy of this array and use one array for enumerating and second for removing. Or you can add all items for removing (which you will find in cicle) in second array and then just remove them by call removeObject:.
Don't store indexes cause after first remove second index can be wrong (if second object has higher index than first).
Related
This code:
server_response = [{id:1},{id:2},{id:3},{id:4}]
I am getting above response from server now I want only the list of ids in one array like
ids = [1,2,3,4];
I know we can do by for loop but it takes long time if thousand of ids inside the response array.
Is there any better way to achieve above equation?
NSArray *result = [yourArray valueForKey:#"id"]
From the documentation for NSArray instance method valueForKey:
Returns an array containing the results of invoking valueForKey: using key on each of the array's objects
NSMutableArray *resultArray = [NSMutableArray array];
for (NSDictionary *dict in server_response) {
[resultArray addObject:[dict objectForKey:#"id"]];
}
Try above code. Hope it will help you. Result array has final values
NSArray *server_response = #[#{#"id":#"1"},#{#"id":#"2"},#{#"id":#"3"},#{#"id":#"4"}];
NSMutableArray *resultArray = [NSMutableArray array];
NSString *birdtemp;
for (NSDictionary *object in server_response) {
birdtemp = object[#"id"];
[resultArray addObject:birdtemp];
}
NSLog(#"%#",resultArray);
OutPut: [
1,
2,
3,
4
]
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]
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
I have a plist that looks like this with a count of 81 "dictionary" items:
I have this code which reads pList into newArray
NSArray *newArray = [[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"DukeCruiseControlTable" ofType:#"plist"]];
When I look at newArray in the debugger I get:
newArray has the right number of elements, so it is reading the right file. But instead of containing the content of each element it is showing just the index of the element (e.g. [3]).
What am I doing wrong?
Being new to iOS I thought perhaps the debugger just showed me the indices of an Array, but when I use the next code to read the array into another array of objects I get an error that indicates that the newArray element is "[3]" or whatever the index is.
for (dukeperfPerfChartLine *object in newArray)
{
[self.perfTable addObject:object];
}
I dont see any problem in reading the file, in debugger it will show only the indices, you can try printing the newArray just after reading from the file as:
NSLog(#"%#",newArray);
For reading the dictionaries from the newArray,I think you should try this:
EDITED:
for (NSDictionary *dict in newArray)
{
NSArray *allKeys = [dict allKeys];
for (NSString *key in allKeys)
{
NSLog(#"%#=%#",key,[dict objectForKey:key]);
}
}
Hope it will help.
A comment to the answer by #Rajeev but as an answer just for the formatting.
Two other methods using different enumeration methods:
Using fast enumeration:
for (NSDictionary *dict in newArray) {
for (NSString *key in dict) {
NSLog(#"%#=%#",key,[dict objectForKey:key]);
}
}
Using an enumeration block:
for (NSDictionary *dict in newArray) {
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(#"%#=%#",key, obj);
}];
}
These produce the same results as the answer by #Rajeev.
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];
}