Get NSArray index number - objective-c

self.listData = [NSArray arrayWithObjects:#"A",#"B",#"C", nil];
How can I get index numbers for listData items?
This code below is used to get listData items string:
c = [NSString stringWithFormat:#"%#",[listData objectAtIndex:indexPath.row];
Any idea?
Thanks

Something like...
NSUInteger index = [listData indexOfObject:#"A"];
From the docs:
Return Value
The lowest index whose
corresponding array value is equal to
anObject. If none of the objects in
the array is equal to anObject,
returns NSNotFound.
Discussion
Objects are considered
equal if isEqual: returns YES.
** Important: If anObject is nil an exception is raised.**

If you can guarantee that the strings in your array are unique, then using indexOfObject: will work. Otherwise, you'll need to use one of the indexesOfObjects* methods such as indexesOfObjectsWithOptions:passingTest: to get a set of all of the indexes containing the object you're interested in.

Related

indexOfObjectIdenticalTo: - Getting junk value

NSString *yes0 = #"yes";
NSString *yes1 = #"YES";
NSString *yes2 = #"Yes";
NSString *yes3 = [NSString stringWithFormat:#"%#",yes1];
NSArray *yesArray = [NSArray arrayWithObjects:#"yes", #"YES", #"Yes", #"YES", nil];
NSArray *yesArray1 = [NSArray arrayWithObjects:yes0, yes1, yes2, yes3, nil];
NSUInteger index;
index = [yesArray indexOfObjectIdenticalTo:yes3];
NSLog(#"\nindex : %d", index); // 1st Output
index = [yesArray1 indexOfObjectIdenticalTo:yes3];
NSLog(#"\nindex : %d", index); // 2nd Output
1st Output
Output i receive is: "2013-07-18 16:42:04.896 Collections - Arrays[2778:f803] index : 2147483647"
2nd Output
Output i receive is: "2013-07-18 16:42:04.896 Collections - Arrays[2778:f803] index : 3"
I get confused due to the outputs i receive. Kindly explain me the process why i get the junk value during the output 1. According me, both arrays are identical with objects. Then why this junk value.
Also having a question:
According to apple, indexOfObjectIdenticalTo: returns - The lowest
index whose corresponding array value is identical to anObject.
Upto my understanding, in yesArray1 - yes1 is same as yes3. My expecting value of output 2 is 1 which gets contradict with the actual printed value (3). Also please let me understand it properly why it is printing 3 rather than 1.
First off, it's not a "junk value", it's the NSNotFound constant.
The first index is not found because yes3 is not in yesArray (it's only in yesArray1) – note that indexOfObjectIdenticalTo: checks for pointer identity, not object equality (unlike indexOfObject:).
indexOfObjectIdenticalTo checks for pointer equality, not object equality. 2147483647 isn't a junk value, it's the value of NSNotFound (which is the defined result if no index is found).
indexOfObjectIdenticalTo : checks for pointer equality
indexOfObject: checks Object equality.
Good Luck !!!

Check duplicate property values of objects in NSArray

I have an NSArray containing objects with a size property.
How can I check if the NSArray has two objects with the same value for size?
Can I do something like:
int i = 0;
for (id item1 in myArray) {
NSDecimalNumber *size1 = [item1 size];
for (id item2 in myArray) {
NSDecimalNumber *size2 = [item2 size];
if ([size1 isEqual:size2]) {
i ++;
}
}
}
if (i > [myArray count]) {
NSLog(#"Duplicate Sizes Exist");
}
Or is there an easier way?
Try this code:
NSSet *myset = [NSSet setWithArray:[myarray valueForKey:#"size"]];
int duplicatesCount = [myarray count] - [myset count];
size here is the object property.
Use NSCountedSet. then add all your objects to the counted set, and use the countForObject: method to find out how often each object appears in your array.
You can check this link also how-to-find-duplicate-values-in-arrays
Hope it helps you
Probably simplest is to sort the array based on the size field and then step through the sorted list looking for adjacent dupes.
You could also "wrap" each object in one that exports the size as its key and use a set. But that's a lot of extra allocations.
But if you only want to know if dupes exist, and not which ones they are, create an NSNumber for each object's size and insert the NSNumbers in a set. The final size will tell you how many dupes.
NSArray *cleanedArray = [[NSSet setWithArray:yourArraywithDuplicatesObjects ] allObjects];
Use Sets this will remove all duplicates objects.Will return NSArrayNSCountedSet and use countForObject: method to find out how often each object appears how many times.

NSSet: return an NSArray of objects sorted by a list of strings on certain property of each object?

I have an NSSet of objects.
Each object in the set is an instance of MyObject with a property called name.
I have another NSArray called nameIndexes which contains name values.
I would like to have a function that takes the NSSet and returns a sorted array sorted using the name property based on its position in the nameIndexes array.
Edit:
Sorry for my misleading, here is an example:
I have a set of MyObject(may not be in the same order):
MyObject1 {name:#"A"}
MyObject2 {name:#"B"}
MyObject3 {name:#"C"}
I have another array of names:
{"B", "A", "C"}
I want an NSArray of:
{MyObject2, MyObject1, MyObject3}
NSSet *set = //your set.
NSArray *nameIndexes = //the array of names for sorting.
NSArray *result = [[set allObjects] sortedArrayUsingComparator:^NSComparisonResult(MyObject *obj1, MyObject *obj2) {
int index1 = [nameIndexes indexOfObject:obj1.name];
int index2 = [nameIndexes indexOfObject:obj2.name];
return [[NSNumber numberWithInt:index1] compare:[NSNumber numberWithInt:index2]];
}];
Not 100% certain what you are asking but this will sort take the set of names and turn it into a sorted array sorted based on the index of the names in a second array.
After edit
Edit... ok, so your edit completely changed the question. Anyway, from the edit you can just do...
NSArray *result = [[set allObjects] sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:"name" ascending:YES]]];
This will take the set and return a sorted array sorted by the name property of the objects in alphabetical order.

NSMutableArray contains Objects

I have to check whether an NSMutableArray contains an object multiple times (for e.g. the array contains 1,2,3,1,4), I want to know how many times 1 is present in the array. I am aware of containsObject: but how to use it for this kind of check?
NSCountedSet may help as you want to track how many times a duplicate value occurs.
http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSCountedSet_Class/Reference/Reference.html#//apple_ref/occ/cl/NSCountedSet
A quick way would be to convert it to an NSSet and then back to an array. NSSets cannot contain duplicates. Alternatively copy the values one by one into a new array using a loop, and each time check that the new array does not contain a copy of the object before adding it.
It depends on your object types, but if they can be used as keys for an NSDictionary, I would create an NSMutableDictionary that points to NSNumber objects containing counts for each object instance. Something like:
NSArray *array = whatever;
NSMutableDictionary *d = [NSMutableDictionary dictionaryWithCapacity:array.count];
for ( id obj in array )
{
NSNumber *number = [d objectForKey:obj];
if ( number == nil )
{
[d setObject:[NSNumber numberWithInt:1] forKey:obj];
}
else
{
[d setObject:[NSNumber numberWithInt:([number intValue]+1) forKey:obj];
}
}
At the end of this code, you are left with an NSDictionary where the keys are your original objects and the values are NSNumbers that contain the number of times that key exists in the original.

iPhone, How can I store a value and a key and lookup by key and index?

I've tried NSMutableDictionary however I don't seem to be able to get an object by index.
Any ideas?
EDIT:
I've trying to create a uitableview sections object, which will store the header titles and be able to increment a counter for the rows. I need to be able to get the counter by index, counter value by title value.
Simplest way is to use 2 collections: dictionary for section infos (row numbers, countries etc) and array for section titles.
NSMutableDictionary *sectionInfos;
NSMutableArray *sectionTitles;
When you need a section info by sectionTitle:
NSDictionary *info = [sectionInfos objectForKey:sectionTitle];
int rowsCount = ((NSArray *)[info objectForKey:#"Countries"]).count;
When you need a section info by sectionIndex:
NSString *title = [sectionTitles objectAtIndex:sectionIndex];
NSDictionary *info = [sectionInfos objectForKey:title];
int rowsCount = ((NSArray *)[info objectForKey:#"Countries"]).count;
When you add a section, add sections info:
[sectionInfos setObject:info forKey:sectionTitle];
and a title to array, so infos and titles will be in sync.
[sectionTitles addObject:sectionTitle];
UPDATE: if the only info needed for section is number of rows:
UPDATE2: added types.
NSMutableDictionary *sectionRowCounts;
NSMutableArray *sectionTitles;
Rows count by sectionTitle:
int rowCount = [[sectionRowCounts objectForKey:sectionTitle] intValue];
Rows count by sectionIndex:
NSString *title = [sectionTitles objectAtIndex:sectionIndex];
int rowCount = [[sectionRowCounts objectForKey:title] intValue];
Adding a section:
[sectionRowCounts setObject:[NSNumber numberWithInt:rowCount] forKey:sectionTitle];
[sectionTitles addObject:sectionTitle];
Dictionaries are not ordered; therefore the objects in them do not have an index.
http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/occ/cl/NSDictionary
You need to use the key to retrieve a particular object from a dictionary. If you need to have the objects in a specific order, then you would probably use NSArray instead.
UPDATE
In your edit, you don't show what tableSectionArray is, but it looks like it's a dictionary (which makes it poorly named). You should use an NSArray, not an NSDictionary, to store what you want. If you need more than one value to be stored, then store an object that contains the values you need. Create a class that has the required values as properties; or, if appropriate, add NSDictionary objects to your array. (Based on how you are trying to assign an element from tableSectionArray, it looks like you do want it to contain dictionaries.) But you need the tableSectionArray itself to be an NSArray.
Yes, keep trying with NSMutableDictionary. It's the data structure you need for that. Can you post your code to see why it's not returning the value you expect?
Example:
NSString *yourvalue = #"Hello!";
NSMutableDictionary *d;
[d setValue:yourvalue forKey:#"yourkey"];
NSString *retrievedvalue = [d valueForKey:#"yourkey"];
// you should get value here