How can I get my object index? I have a dictionary containing arrays and inside the arrays i have multiple dictionary.
My data structure(eg):
Student ------ NSDictionary
Item 0 ------ NSArray<br>
Name ----- Grace<br>
Age ----- 20<br>
Item 1 ------ NSArray<br>
Name ----- Anne<br>
Age ----- 21<br>
So for example, I have the value of the name, Grace, and I want to get the value of the object index array (in this case, item 0). How can I do so?
I've used the indexOfObject however the results I got back is 2147483647, which i think it means nsnotfound. So i think it doesnt work for this case.
This are my codes:
NSMutableDictionary* namevalue = [[NSMutableDictionary alloc] init];
namevalue = [somedict objectForKey:#"Name"];
int arryindex;
arryindex = [somearray indexOfObject:namevalue];
NSLog(#"Array Index:%i", arryindex);
Can anyone help? Thank you so much!
In your code you forgot to include the creation of somedict and somearray. The problem may be there.
Also, you don't need to assign namevalue an empty dictionary and then the actual dictionary inside the array.
Check this fragment of working code:
NSUInteger idx;
NSDictionary *john = [NSDictionary dictionaryWithObjectsAndKeys:#"John", #"name",
[NSNumber numberWithInt:23], #"age", nil];
NSDictionary *jane = [NSDictionary dictionaryWithObjectsAndKeys:#"Jane", #"name",
[NSNumber numberWithInt:24], #"age", nil];
NSArray *students = [NSArray arrayWithObjects:john, jane, nil];
idx = [students indexOfObject:john];
NSLog(#"john is at: %i", idx == NSNotFound ? -1 : idx); /* 0 */
idx = [students indexOfObject:jane];
NSLog(#"jane is at: %i", idx == NSNotFound ? -1 : idx); /* 1 */
Now, try with an object not present in the array:
NSDictionary *mary = [NSDictionary dictionaryWithObjectsAndKeys:#"Mary", #"name",
[NSNumber numberWithInt:22], #"age", nil];
idx = [students indexOfObject:mary];
NSLog(#"mary is at: %i", idx == NSNotFound ? -1 : idx); /* -1 Not found */
And finally with a new object but created as an exact duplicate of an object already present in the array:
NSDictionary *maryjane = [NSDictionary dictionaryWithObjectsAndKeys:#"Jane", #"name",
[NSNumber numberWithInt:24], #"age", nil];
idx = [students indexOfObject:maryjane];
NSLog(#"maryjane is at: %i", idx == NSNotFound ? -1 : idx); /* 1 */
The method indexOfObject will use isEqual: to compare objects. You can verify that the new object will be considered as equal to the one inside the array:
NSLog(#"jane is maryjane? %i", [jane isEqual:maryjane]); /* 1 */
If I understood correctly, you're looking for a way to find object index in NSDictionary based on the value of property that object has, right?
E.g. your students dictionary has a student with name Grace and you would like to know at which index the student object with name Grace is stored...
If above is true, here's my (incomplete and rough) solution which works only for objects with NSString properties, but once you get the idea below, I think you'll be able to modify code to match your needs.
- (NSInteger)indexOfObjectWithPropertyValue:(id)value inDictionary:(NSDictionary *)dict {
NSInteger objectIndex = 0;
unsigned int outCount, i;
for (id key in dict) {
id objForKey = [dict objectForKey:key];
Class lender = [objForKey class];
objc_property_t *properties = class_copyPropertyList(lender, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
id v = [objForKey valueForKey:[NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding]];
if ([v isKindOfClass:[value class]] && [v isEqual:value]) {
return objectIndex;
}
}
objectIndex++;
}
return NSNotFound; // i.e. NSIntegerMax
}
and don't forget to include runtime header:
#import <objc/runtime.h>
My code may and probably have some issues:
the most obvious isEqual: method which needs to compare properties' values.
above code does not cover a situation when there are many objects with same value (like many students with the same name!)
???
I hope my "answer" will make it easier for you to implement what you need.
Related
I have two array of dictionaries and i want to compare them
Actually the dictionary structure is like the interest list of Facebook, like below
I want to find out the common interest between me and my friend
I retrieved the interest list of both user, but while I am comparing the dictionary of interests as the created_time differs so I am not getting the common dictionary
category = "Musical instrument";
"created_time" = "2011-06-11T09:10:07+0000";
id = 113099055370169;
name = Guitar;
and
category = "Musical instrument";
"created_time" = "2013-09-27T06:02:28+0000";
id = 113099055370169;
name = Guitar;
Can anybody suggest any efficient way to do this
Now I am using but it is not giving me the common interests as created_time different
for (int count = 0; count < [arrFriendsInterest count]; count++)
{
NSDictionary *dictFriend = [arrFriendsInterest objectAtIndex:count];
if ([arrMyIntrest containsObject:dictFriend]) {
[arrMutualInterest addObject:dictFriend];
}
}
where arrFriendsInterest is array of dictionaries containing friend's interest
and arrMyIntrest is the array of dictionaries containing my interests×Comments may only be edited for 5 minutes×Comments may only be edited for 5 minutes×Comments may only be edited for 5 minutes
First of all are you store that data in NSArray?
If YES then please use following code much more easily to use.
// Do any additional setup after loading the view, typically from a nib.
NSArray *ar1 = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:#"Musical instrument",#"category",#"2011-06-11T09:10:07+0000",#"created_time",#"113099055370169",#"id", #"Guitar",#"name", nil], nil];
NSArray *ar2 = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:#"Musical instrument",#"category",#"2013-09-27T06:02:28+0000",#"created_time",#"113099055370169",#"id", #"Guitar",#"name", nil], nil];
NSMutableSet* set1 = [NSMutableSet setWithArray:ar1];
NSMutableSet* set2 = [NSMutableSet setWithArray:ar2];
[set1 unionSet:set2]; //this will give you only the obejcts that are in both sets
NSArray* result = [set1 allObjects];
NSLog(#"%#",[result mutableCopy]);
Happy Coding.!!!
This assumes that you only need to compare "id" values:
NSArray* myIds = [arrMyInterest valueForKey:#"id"];
for (int count = 0; count < [arrFriendsInterest count]; count++) {
NSDictionary *dictFriend = [arrFriendsInterest objectAtIndex:count];
// Not clear whether "id" is NSString or NSNumber -- use whichever
NSString* friendId = [dictFriend valueForKey:#"id"];
if ([myIds containsObject:friendId]) {
[arrMutualInterest addObject:dictFriend];
}
}
instead of using NSDictionary why don't using custom classes?
You can have a lot of benefits:
code completion
compile-time checking
custom isEqual method
code is self-explained
'm facing problem to sort the values based on key using dictionary object. Actually what i am storing is, each dictionary object having different data type in that dictionary all the data type taking as a string how to convert this string type to specific data type and sort it price vise, my code and out put is bellow, Please help me on this one.
-(IBAction)PriceSort:(id)sender
{
NSSortDescriptor * sort = [[NSSortDescriptor alloc] initWithKey:#"Price" ascending:true] ;
NSArray *sa = [symbolArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
NSLog(#"price=%#",sa);
}
out put
{
volume = 2496752;
Yield = "10.49";
MarCap = 829;
Price = "0.715";
Symbol = SAIPI;
},
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"price"
ascending:YES selector:#selector(localizedStandardCompare:)] ;
Please replace this one and try , hope its works .
-(void)sort
{
//This is the array of dictionaries, where each dictionary holds a record
NSMutableArray * array;
//allocate the memory to the mutable array and add the records to the arrat
// I have used simple bubble sort you can use any other algorithm that suites you
//bubble sort
//
for(int i = 0; i < [array count]; i++)
{
for(int j = i+1; j < [array count]; j++)
{
NSDictionary *recordOne = [array objectAtIndex:i];
NSDictionary *recordTwo = [array objectAtIndex:j];
if([[recordOne valueForKey:#"price"] floatValue] > [[recordTwo valueForKey:#"remaining"] floatValue])
{
[array exchangeObjectAtIndex:i withObjectAtIndex:j];
}
}
}
//Here you get the sorted array
}
Hope this helps.
I have an application in which i am having the details of the members as a dictionary.i want to add an array with particular object from the dictionary.The response i am having is like this,
{
500 = {
name = baddd;
status = "<null>";
};
511 = {
name = abyj;
status = "Hi all...:-)";
};
512 = {
name = abyk;
status = fdffd;
};
}
I want to create an array with the results of name only.i have tried like this
for(int i=0;i<=self.currentChannel.memberCount;i++)
{
NSString *name=[NSString stringWithFormat:#"%#",[self.currentChannel.members objectForKey:#"name"]] ;
NSLog(#"%#",name);
[searchfriendarray addObject:name];
}
NSLog(#"%#",searchfriendarray);
but the value added is null. can anybody help me ?
Traverse objectEnumerator to get the values (inner dictionaries). Then just add the value of "name" to the resulting array. Example (assuming the dictionary is named d):
NSDictionary* d = ...
NSMutableArray* array = [NSMutableArray arrayWithCapacity:d.count];
for(NSDictionary* member in d.objectEnumerator) {
[array addObject:[member objectForKey:#"name"]];
}
Krumelur was faster than me ;) He is right by saing that you should traverse the dictionary values first. In your implementation you don't reference your counter variable i somewhere, so the NSString name is the same in each iteration.
This may help you..
// here you can get Array of Dictionary First
NSArray *arr = [[NSArray alloc] initWithContentsOfFile:#""]; // get array first from your response
NSDictionary *temp = [[NSDictionary alloc] initWithDictionary:self.currentChannel.members];
for(int i=0;i<=self.currentChannel.memberCount;i++)
{
NSDictionary *temp = [arr objectAtIndex:i];
NSString *name=[NSString stringWithFormat:#"%#",[temp objectForKey:#"name"]] ;
NSLog(#"%#",name);
[searchfriendarray addObject:name];
}
NSLog(#"%#",searchfriendarray);
Thanks.
I am trying to filter a NSMutableArray. Search array for items by certain country. I have tried NSpredicate which works great however I need to re-use the original array which I cannot with NSpredicate. So I am trying the below code.
Q. What is the best way to filter an NSMutableArray keeping the original array intact?
//The following code works
filteredArray = [[NSMutableArray alloc] init];
unsigned int i;
for (i = 0; i < [appDelegate.arrayToBeFiltered count]; i++) {
id session = [appDelegate.ads objectAtIndex: i];
id Country = [[appDelegate.arrayToBeFiltered objectAtIndex: i] TheCountry];
[filteredArray addObject: session];
However when I add the if statement as below I get index beyond bounds
filteredArray = [[NSMutableArray alloc] init];
unsigned int i;
for (i = 0; i < [appDelegate.arrayToBeFiltered count]; i++) {
id session = [appDelegate.ads objectAtIndex: i];
id Country = [[appDelegate.arrayToBeFiltered objectAtIndex: i] TheCountry];
if (Country == #"United States"){
[filteredArray addObject: session];
}
}
Use - (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate
As a side-note, in the code above you probably mean to do this [Country isEqualToString: #"United States"]
As an extra side note - don't capitalise variables and method names. Just a style thing but capitalisation is usually reserved for Class names
I have a NSMutableArray:
NSMutableArray *temp = //get list from somewhere.
Now there is one method objectAtIndex which returns the object at specified index.
What I want to do is that, I want to first check whether an object at specified index exists or not. If it exists than I want to fetch that object. Something like:
if ([temp objectAtIndex:2] != nil)
{
//fetch the object
}
But I get exception at the if statement saying that index beyond bound.
Please anyone tell me how to achieve this.
you cannot have 'empty' slots in an NSArray. If [myArray count]==2 ie array has two elements then you know for sure that there is an object at index 0 and an object at index 1. This is always the case.
Check the length first using the count method.
if ([temp count] > indexIWantToFetch)
id object = [temp objectAtIndex:indexIWantToFetch];
you could do this way:
When you initialize, do something like:
NSMutableArray *YourObjectArray = [[NSMutableArray alloc] init];
for(int index = 0; index < desiredLength; index++)
{
[YourObjectArray addObject:[NSNull null]];
}
Then when you want to add but check if it already exists, do something like this:
YourObject *object = [YourObjectArray objectAtIndex:index];
if ((NSNull *) object == [NSNull null])
{
/// TODO get your object here..
[YourObjectArray replaceObjectAtIndex:index withObject:object];
}
Just check that the index is >= 0 and < count
Returns the number of objects currently in the receiver.
- (NSUInteger)count
int arrayEntryCount = [temp count];
First of all you check the length of array-
NSMutableArray *temp = //get list from somewhere.
now check-
if(temp length)
{
Your objectclass *obj = [temp objectAtIndex:indexnumber];
// indexnumber is 0,1,2 ,3 or anyone...
}