I have a NSMutableArray "coordinates" which gives me values like this
2014-01-11 09:52:15.479 DreamCloud[397:70b] (
{
1000 = {
Linecolor = 0X6495ED;
Lines = "4-s";
Xcord = "77.000000";
Xposition = "54.500000";
Ycord = "111.500000";
Yposition = "51.500000";
};
},
{
1001 = {
Linecolor = 0X6495ED;
Lines = "4-s";
Xcord = "45.000000";
Xposition = "42.500000";
Ycord = "417.000000";
Yposition = "54.000000";
};
},
{
1000 = {
Linecolor = 0X6495ED;
Lines = "4-s";
Xcord = "73.000000";
Xposition = "50.500000";
Ycord = "111.000000";
Yposition = "51.000000";
};
}
)
Within this I need ti remove the values for 1001 and recreate the array without 1001 . How do I do this.I am new in ios so I did not figure out how to do this .
for (NSMutableDictionary *deltag in deletelinearray)
{
NSMutableDictionary *gettagsdeleted = [deltag objectForKey:[NSString stringWithFormat:#"%d",myV.tag]];
NSLog(#"%#",gettagsdeleted);
int starttag=[gettagsdeleted objectForKey:#"Starttag"];
int endtag=[gettagsdeleted objectForKey:#"Endtag"];
}
NSLog(#"%#",coordinates);
Above is the code where in "coordinates " I get the array and start-tags and end-tags are 1000, 1001 . In coordinates I don't know the index as Kumar Kl said .
Consider your array name is coorditates
for (NSDictionary *dict in coorditates) {
if ([dict objectForKey:[NSString stringWithFormat:#"%d",1001]]) {
[coorditates removeObject:dict];
break;
}
}
You can also use NSPredicate but, for that coorditates array must be NSMutableArray
NSPredicate *pred = [NSPredicate predicateWithFormat:#"ANY self.#allKeys != %#", #"1001"];
[coorditates filterUsingPredicate:pred];
Try this for loop instead. Instead of selecting the object with the key it removes it.
for (NSMutableDictionary *deltag in deletelinearray)
{
[coordinates removeObjectForKey:[NSString stringWithFormat:#"%d",myV.tag]];
}
It is not a good coding practice to modify(insert or delete) the items in array while enumerating it. So first find your index and then delete it.
You don't need to create a new array, once the details with "1001" is removed. You already have an update array.
NSString *deleteKey=#"1001";
__block int deleteIndex=-1;
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
for (NSString *key in [obj allKeys]) {
if([key isEqualToString:deleteKey]){
deleteIndex=idx;
*stop=YES;
}
}
}];
if(deleteIndex>=0){
[arr removeObjectAtIndex:deleteIndex];
}
You want to call the removeObjectAtIndex: function, but it appears your array contains dictionary objects and you want to remove the one with the key 1001. What you want to avoid is removing the object WHILE looping through the array.
So, what I would do is create a variable that will hold the index of the item once you find it, then loop through the array and once you find the object that it matches store the index and break. After, you shouldn't need to recreate the array after you remove the item, removing the object at the index you provide the above function will do just that for you. In your case, you'll want to do the following:
NSString *key = #"1001";
for (NSInteger index = 0; index < array.count; index++) {
NSDictionary *dictionary = coordinates[index];
if (dictionary[key]) {
indexToDelete = index;
break;
}
}
[coordinates removeObjectAtIndex:1001];
int i = 0;
for (NSDictionary *dict in coorditates)
{
if ([dict objectForKey:#"1001"])
{
[coorditates removeObjectAtIndex:i];
}
i++;
}
Related
I have an NSMutableArray that contains an object of a class model in each position like this.
The class model contains 2 types of information, which we will call id and name.
So, in every location of my NSMutableArray I have an object that contains 2 information.
Then, in the first position of my NSMutableArray I have
{
id = 1;
name = "Dan"; //this is the first object in NSMutableArray
}
In the second position of NSMutableArray, I have:
{
id = 1;
name = "Luca";
}
In the third position
{
id = 2;
name = "Tom";
}
and so on..
Ok, my goal is to make the union of identical IDs between the various objects within the SNMutableArray but it's too difficult!
For example, if I have:
{
id = 1;
name = "Tom";
}
{
id = 1;
name = "Luca";
}
{
id = 2;
name = "Steve";
}
{
id = 2;
name = "Jhon";
}
{
id = 3;
name = "Andrew";
}
The goal is:
{
id = 1;
name = "Tom";
name = "Luca";
}
{
id = 2;
name = "Steve";
name = "Jhon";
}
{
id = 3;
name = "Andrew";
}
Any ideas? would like to use this in the cellForRowAtIndexPath method and I tried to write this: (cm is my class model and myArray is the NSMutableArray which contains an object of cm class)
ClassModel *cm = [myArray objectAtIndex:indexPath.row];
NSMutableArray * resultArray = [NSMutableArray new];
NSArray * groups = [array valueForKeyPath:cm.ID];
for (NSString * groupId in groups)
{
NSMutableDictionary * entry = [NSMutableDictionary new];
[insert setObject: groupId forKey: # "groupId"];
NSArray * groupNames = [array filteredArrayUsingPredicate: [NSPredicate predicateWithFormat: # "groupId =% #", groupId]];
for (int i = 0; i <groupNames.count; i ++)
{
NSString * name = [[groupNames objectAtIndex: i] objectForKey: # "name"];
[entry setObject: name forKey: [NSS string stringWithFormat: # "name% d", i + 1]];
}
[resultArray addObject: entry];
}
NSLog (# "% #", resultArray);
But this does not work..maybe because each element in my array is an object?? .. Help!
You have the right basic idea, but you shouldn't try and do this in cellForRowAt. Rather, you need to create a new array that has the data in the required structure and use that array as the source for your tableview. You will also need to create a new class to put in the array; one that has an id and an NSMutableArray for the names (I won't show this but I will call it GroupClassModel)
Use something like:
NSMutableDictionary *groups = [NSMutableDictionary new]
for (ClassModel *cm in array) {
GroupClassModel *gcm = groups[cm.id];
if (gcm == nil) {
gcm = [GroupClassModel new];
gcm.id = cm.id
groups[cm.id] = gcm
}
[gcm.names addObject:cm.name];
}
NSArray *groupedName = [groups allValues];
// Finally, sort groupedName by id if that is required.
How would I get "Dog" from the following dictionary?
{
Id = "123";
Animal = [{
Id = "456";
Type = "Dog";
Sound = "Bark";
},
{
Id = "789";
Type = "Cat";
Sound = "Meow";
}]
}
I tried
NSString *firstAnimalType = dictionary[#"Animal"][#"Type"];
However since there are multiple animals, it can't recognize what I am trying to find. How would I get the first animal out of the list so that I can access its type? Thanks!
You can use some thing like this, first get animal object and if it exists then find its type from it
NSDictionary *firstAnimal = [dictionary[#"Animal"] firstObject];
if(firstAnimal) //in case your firstAnimal is Empty or it may be nil then may create any unwanted issues in further code so just check it first.
{
NSString *firstAnimalType = firstAnimal[#"Type"];
}
Enumeration method will help and you can stop when and where you want
[myDict[#"Animal"] enumerateObjectsUsingBlock:^(id _Nonnull objList, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(#"%#",objList[#"Type"]);
*stop = YES; //You can stop where you want
}];
You can simply access the first element of the array with castings and get its Type value.
NSString *firstAnimalType = ((NSDictionary *)[((NSArray *)dictionary[#"Animal"]) objectAtIndex: 0])[#"Type"];
for (NSDictionary *animal in dictionary[#"Animal"]) {
NSString *type = animal[#"Type"];
if ([type isKindOfClass:[NSString class]] && [type isEqualToString:#"Dog"]) {
// Dog found
}
}
Here you go:
NSArray *aryFinalAni = [dicMain valueForKey:#"Animal"];
NSArray *aryType = [aryFinalAni valueForKeyPath:#"Type"];
if([aryType containsObject:#"Dog"])
{
int indexOfDog = (int)[aryType indexOfObject:#"Dog"];
NSMutableDictionary *dicDog = [aryFinalAni objectAtIndex:indexOfDog];
NSLog(#"%#",dicDog);
}
else
{
NSLog(#"There is no Dog found.");
}
Try this code:
{
Id = "123";
Animal = [{
Id = "456";
Type = "Dog";
Sound = "Bark";
},
{
Id = "789";
Type = "Cat";
Sound = "Meow";
}]
}
1> NSArray *items = dictionary["Animal"];
2>
NSPredicate *predicate1 = [NSPredicate predicateWithFormat: #"Type CONTAINS[cd] %#", "Dog"];
NSArray *arrData = [items filteredArrayUsingPredicate:predicate1];
if arrData.count > 0 {
dictionary = [arrData objectAtIndex:0];
}
Result:
{
Id = "456";
Type = "Dog";
Sound = "Bark";
}
Hi i have two nsarrays.
Array A:
arrProductSelection = [[NSArray alloc]initWithObjects:#"English",#"German",#"Russian",#"Chinese",#"Spanish",#"French",#"French",#"French",#"French",#"French",#"French",#"French",#"French",nil];
Array B:
arrProductSelectionB = [[NSArray alloc]initWithObjects:#"deselcted",#"selected",#"selected",#"selected",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",nil];
I need to compare two arrays and get the value from array A by comparing with array B having value as selected. That is i should get german,chinese and russian sepearted by comma as nsstring.
Try this:
NSMutableArray *arrSelected = [[NSMutableArray alloc] init];
NSArray *arrProductSelection = [[NSArray alloc]initWithObjects:#"English",#"German",#"Russian",#"Chinese",#"Spanish",#"French",#"French",#"French",#"French",#"French",#"French",#"French",#"French",nil];
NSArray *arrProductSelectionB = [[NSArray alloc]initWithObjects:#"deselcted",#"selected",#"selected",#"selected",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",#"deselcted",nil];
for(int i = 0; i< arrProductSelectionB.count-1;i ++) {
if ([arrProductSelectionB[i] isEqualToString:#"selected"]) {
[arrSelected addObject:arrProductSelection[i]];
}
}
NSString *strSelected = [arrSelected componentsJoinedByString:#","];
NSLog(#"%#", strSelected);//output: German,Russian,Chinese
If you can make this type of array then manage easly.
(
{
flag = deselcted;
name = English;
},
{
flag = selected;
name = German;
},
{
flag = deselcted;
name = Russian;
},
{
flag = deselcted;
name = Chinese;
}
)
==> Array[(dictionary),(dictionary),.....]
if you need result in an array, Here is the function:
NSMutableArray*resultArray=[[NSMutableArray alloc]init];
for(int i=0; i<arrProductSelectionB.count;i++){
if ([[arrProductSelectionB objectAtIndex:i]isEqualToString:#"selected"]) {
[resultArray addObject:[arrProductSelection objectAtIndex:i]];
}
}
resultArrayhave the values which you need.
first i would make sure both arrays have same counters for safety something like
if (arrProductSelection.count == arrProductSelectionB) {
//than all you need is one for cycle something like :
for (int i = 0; i < arrProductionSelectionB.count; i++) {
if ([arrProductionSelectionB[i] isEqualToString: #"selected"]) {
do something magically with arrProductSelection[i];
}
}
}
This question already has answers here:
NSDictionary with ordered keys
(9 answers)
Closed 8 years ago.
I saw many examples on SO but I'm not sure if it applies to this situation. Everywhere it says NSMutableDictionries are not guaranteed an order...but I'm getting my data from the server...so my NSMuteDic looks like this:
{
joe = (
{
fromName = joe;
id = 25;
theMessage = "this is going to be a really big message...";
timeAdded = "2014-04-07 21:08:12";
toName = "me";
},
{
fromName = joe;
id = 10;
theMessage = "why???";
timeAdded = "2014-04-05 20:10:04";
toName = "me";
}
);
bob = (
{
fromName = "me";
id = 24;
theMessage = "blah blah";
timeAdded = "2014-04-06 21:15:06";
toName = bob;
},
{
fromName = bob;
id = 22;
theMessage = message;
timeAdded = "2014-04-06 20:11:57";
toName = "me";
}
);
//more entries here
}
What I want to do is change the order...put bob first and joe second. Is this really impossible to do? I saw many very complex solutions...there's no easy way to do this with just a for loop?
cellForRowAtIndexPath:
NSMutableArray *temp = [myDict objectForKey:keys[indexPath.row]];
cell.Message.text = [[reverse lastObject] valueForKey:#"theMessage"];
cell.dateTime.text = [[reverse lastObject] valueForKey:#"timeAdded"];
return cell;
This is how I'm using it...and when a row is selected I pass the array to the next view controller. The reason why I want to reorder is if a new message will be inserted in the pushed view controller, I want that dictionary to be first in the list so the root view controller can be reordered.
NSArray *keys = [myDict allKeys];
[myDict removeObjectForKey:to];
NSMutableDictionary *temp = [NSMutableDictionary dictionaryWithCapacity:[myDict.count];
temp = myDict;
[myDict removeAllObjects];
[myDict setObject:currentDict forKey:to];
for (int i=0; i<temp.count; i++) {
[myDict setObject:[temp valueForKey:keys[i]] forKey:keys[i]];
}
That's not working because it looks like since myDict is a NSObject, temp gets changed every time myDict changes...from the looks of it the logic should work but it isn't...
NSMutableDictionary is not ordered. There is nothing you can do to guarantee the order of keys because NSDictionary makes no attempt to preserve any particular ordering. To go over a dictionary in a particular order, you have to make an array of the keys that is in the order you want, then iterate that and fetch the corresponding values.
// Get the keys
NSArray *keys = [myDict allKeys];
// Sort the keys
NSArray *sortedArray = [NSArray arrayWithArray:[keys sortedArrayUsingComparator:^(NSString* a, NSString* b) {
return [a compare:b];
}]];
// Iterate the dictionary
for (NSUInteger n = 0 ; < [sortedArray count]; n++) {
id value = [myDict objectForKey:[sortedArray objectAtIndex:n]];
}
I asked a similar question to test an Array of Bool values here but now I have changed it so the values are now Integer values and I want to see if any of them are positive.
Example, I add 10 new objects in a loop like below, then at some point some may change and then I need to do a test. It may be that I do not use NSNumber, as long as I cna get an int out of it.
// I create an array like
NSMutableArray *MyArray = [[NSMutableArray alloc]init];
for (int count = 0; count < 10; count++)
{
[MyArray addObject:[NSNumber numberWithInt:0]];
}
// At some point I change a value or two
[MyArray replaceObjectAtIndex:3 withObject:[NSNumber numberWithInt:5]];
....
....
....
....
[MyArray replaceObjectAtIndex:3 withObject:[NSNumber numberWithInt:7]];
if([MyArray containsPositiveObject])
{
// Get the integer
int MyValue = [MyArray[4]integerValue];
}
EDIT
I have tried this and it works but wondered if there was a faster method.
if([self containsPositiveValue:selectedItems])
{
// Do my stuff
}
And then
-(bool)containsPositiveValue:(NSArray *)numberArray
{
bool result = NO;
for (NSNumber *obj in numberArray)
{
if([obj integerValue])
{
result = YES;
break;
}
}
return result;
}
Try this.
NSArray *array = #[ #(-1) , #(-3) , #(0) , #(-4) , #(2) , #(-1) ]; // zero is not positvie or negitive
NSArray *newArray = [array filteredArrayUsingPredicate: [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return ( [evaluatedObject isKindOfClass:[NSNumber class]] && ([evaluatedObject integerValue] > 0) );
return NO;
}]];
if (newArray.count)
{
NSLog(#"There are positive values");
}
else
{
NSLog(#"There are no positive values") ;
}
Surely the simplest way would be to go:
NSArray * array = #[#(-1), #(-5), #(-5)];
for (NSNumber * number in array) {
if (number.intValue > 0) {
NSLog(#"Positive Values");
// Add custom code here
break;
}
}
This will then check if at least one item in the array is greater than zero and custom code can then be implemented.
I suppose it depends if you want to perform something if there are no positive values and something different if there is?
You could always add something like this:
NSArray * array = #[#(-1), #(-5), #(-5)];
NSInteger largestValue = 0;
for (NSNumber * number in array) {
if (number.intValue > largestValue) {
largestValue = number.intValue;
}
if (largestValue > 0) {
break;
}
}
if (largestValue > 0) {
NSLog(#"Positive Value");
}
else {
NSLog(#"All Negative Values");
}
Anyway it gets more complicated the more complicated you want it to work but it should be incredibly simple