Am confused with the use of this method and the documentation that lists it as a (void) method.
"on return the index path's indexes"
where does it return anything too?
Should it not be:
- (NSIndexPath *)getIndexes:(NSUInteger *)indexes
getIndexes:
Provides a reference to the index path’s indexes.
- (void)getIndexes:(NSUInteger *)indexes
Parameters
indexes
Pointer to an unsigned integer array. On return, the index path’s indexes.
Availability
Available in iOS 2.0 and later.
Declared In
NSIndexPath.h
You have to allocate the NSUInteger array of size [indexPath length] and pass it as argument. The return value will be written there. You have to release that array yourself or do nothing it was created on stack like this:
NSUInteger array[[indexPath length]];
[indexPath getIndexes: array];
Maybe the next sentence explains the reason
It is the developer’s responsibility to allocate the memory for the C array.
It's actually a pointer to a C array that will be filled for you with the indexes, so there's no reason to additionally return it from the function - you already know its address.
You can use the function as follows
NSUInteger indexCount = [indices count];
NSUInteger buffer[indexCount];
[indices getIndexes:buffer maxCount:indexCount inIndexRange:nil];
You send that message to an instance of NSIndexPath, so getting one back wouldn't help. The -getIndexes: method fills the array 'indexes' with the indexes from the index path. So you'd do something like:
NSUInteger *indexes = calloc([indexPath length], sizeof(NSUInteger));
[indexPath getIndexes:indexes];
After that, indexes will be filled with the index values that are in indexPath.
Max, Thomas and Caleb, I have tried all three ways and cannot get anything to work, so maybe fired off the accepted solution too quick.....but probably more likely I just don't get it? I can't get the right size of the array in order to loop through it to access the required rows in my table. I would have though that calloc([indexPath length], sizeof(NSUInteger)) would for a group with 5 rows return an array with 5 rows with each row holding NSUIntegr.....or am of so far off beam it embarrassing?
Related
I'm adding an object to a NSMutableArray like this:
[array addObject:myObject];
I now want to send a reference to my delegates of the Array Index where this object was added.
Is there an easy way to find out the index where my object was added in the array so that later I can call
[array objectAtIndex:index]
to get a reference back for it?
Thanks!
Rather than passing the index of an object (which could be incorrect) to your delegate, pass a reference to the object itself. If the delegate needs the index of the object in the array, it can figure it out itself using -indexOfObject: as Antonio MG describes. The index of any given object in a mutable array can change as objects are added, inserted, and deleted. Counting on indices to remain valid over any period of time is like leaving a jelly sandwich on the counter -- it's sure to attract bugs.
You need to serialize access to a mutable array and -addObject: always adds the object to the end of the array. Given those two assertions, you know the index of the next added object will always be the current length of the array. So the following will hold true:
NSUInteger nextIndex = [array count];
[array addObject:myObject];
// you can now tell your delegates that nextIndex is the index of myObject
Use this method for that:
index = [animalOptions indexOfObject:myObject];
The latest added object should be at [array count] - 1 index. You can always rely on "count - 1" scheme to determine the last index.
If you call addObject you always add the object at the end (so count - 1).
You can use "insertObject:atIndex:" to specify an index.
For your question: indexOfObject:
Direct after adding the object's index is array.count -1 .
i am trying to get index of an array through indexOfObject method as follows but when i try to log the value to test the index i get a garbage value.. for testing purposes i am having an array with values {57,56,58..} to get an index of lets say 56,
NSNumber *num = [NSNumber numberWithInteger:56];
NSInteger Aindex = [myArray indexOfObject:num];
NSLog(#" %d",Aindex);
the value i get is something like 2323421. what am i possibly doing wrong??
The index returned by indexOfObject will be the first index for an occurence of your object. Equality is tested using isEqual method.
The garbage value you get is probably equal to NSNotFound.
Try testing anIndex against it. The number you are looking for isn't probably in your array :
NSNumber *num=[NSNumber numberWithInteger:56];
NSInteger anIndex=[myArray indexOfObject:num];
if(NSNotFound == anIndex) {
NSLog(#"not found");
}
or log the content of the array to be sure :
NSLog(#"%#", myArray);
Folks,
When an object is not found in the array the indexOfObject method does NOT return a 'garbage' value. Many systems return an index of -1 if the item is not found.
However, on IOS - because the indexOfObject returns an UNSIGNED int (aka NSUInteger) the returned index must be greater than or equal to zero. Since 'zero' is a valid index there is no way to indicate to the caller that the object was not found -- except by returning an agreed upon constant value that we all can test upon. This constant agreed upon value is called NSNotFound.
The method:
- (NSUInteger)indexOfObject:(id)anObject;
will return NSNotFound if the object was not in the array. NSNotFound is a very large POSITIVE integer (usually 1 minus the maximum int on the platform).
NSNumber *num1 = [NSNumber numberWithInt:56];
NSNumber *num2 = [NSNumber numberWithInt:57];
NSNumber *num3 = [NSNumber numberWithInt:58];
NSMutableArray *myArray = [NSMutableArray arrayWithObjects:num1,num2,num3,nil];
NSNumber *num=[NSNumber numberWithInteger:58];
NSInteger Aindex=[myArray indexOfObject:num];
NSLog(#" %d",Aindex);
Its giving the correct output, may be u have done something wrong with storing objects in ur array.
Try this:
NSArray's indexOfObject: method. Such as the following:
NSUInteger fooIndex = [someArray indexOfObject: someObject];
If you're using Swift and optionals make sure they are unwrapped. You cannot search the index of objects that are optionals.
I just checked. Its working fine for me. Check if your array has the particular number. It will return such garbage values if element is not present.
indexOfObject methord will get the index of the corresponding string in that array if the string is like #"Test" and you find like #"TEST" Now this will retun an index like a long number
Question: How do I get the index of the current Object in an NSEnumerator iteration?
(I don't want to keep track of things using an integer counter or use a for loop due to speed reasons. I did it before I just cannot remember how I did it...)
It is doubtful that using an integer counter in a for loop will cause speed problems. It is more likely to be slower to try and find the index of a given object from an enumerator than it is to just keep a record of the index yourself. If you want to bypass repeated message dispatch, have a look at NSArray's getObjects:range: method.
size_t count = [myArray count];
id *objects = calloc(count, sizeof(id));
[myArray getObjects:objects range:NSMakeRange(0, count)];
// if you have a very large count, you'll save doing an
// "objectAtIndex:" for each item.
for (int i = 0; i < count; i++)
[objects[i] doSomething];
free(objects);
You'll probably only see a minimal performance difference for incredibly large arrays, but don't underestimate the optimisations under the hood. Even the documentation for getObjects:range: discourages using this technique for this purpose.
NSArray's indexOfObject: will iterate over all the elements until one returns YES from isEqual: message (which may include further message sending).
You are asking for an index, so we can assume that you are using an array. If so:
[array indexOfObject:currentObject];
will work for most cases (but not all). It would be faster overall to switch to using a normal for loop with an int counter, however.
I have a NSMutableArray, I want to insert data inside it, the problem is first I want to check if the index where I'm inserting the data exists or not. How to do that?
I try something like that but nothing is working:
if ([[eventArray objectAtIndex:j] count] == 0)
or
if (![eventArray objectAtIndex:j])
if (j < [eventArray count])
{
//Insert
}
NSArray and NSMutableArray are not sparse arrays. Thus, there is no concept of "exists at index", only "does the array have N elements or more".
For NSMutableArray, the grand sum total of mutable operations are:
- (void)addObject:(id)anObject;
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
- (void)removeLastObject;
- (void)removeObjectAtIndex:(NSUInteger)index;
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
All other mutability methods can be expressed in terms of the above and -- more specifically to your question -- removing an object does not create a hole (nor can you create an array with N "holes" to be filled later).
I've given a brief implementation of a sparse array in this question: Sparse Array answer
if i try to access a nsmutableArray with objectAtIndex:x and if i have no object at this index, my app always crash.
So my question is: how can i check, if there is something at this index, without crashing the app?
I hope your understand my question.
Thanks, Alex
Check if your index is in array's bounds range:
if (index >=0 && index < [myArray count])
...
NSArray has a method called "count".
Call count on your mutable array and it will tell you the number of elements in the array.
You have two options: Use the count method to ensure you're within the bounds of the array, or catch the exception when you try to use objectAtIndex: Checking the range with count will be much lower overhead than catching the exception.
In case you didn't know - there are no "holes" allowed in an NSArray - the objects from index 0 to the end of the array ([array count]-1) will all be accessible.
If you are within the array's bounds, you will always have an object at a specific index between 0 and [array count], as the array cannot have gaps of nil values in it.
Try this
for(i=0; i< [myMutableArrayObject count]; i++) {
NSLog(#"%#",[[myMutableArrayObject objectAtIndex: i] myMethodDefined]);
}
Here, we are using a method predefined called count which returns the number of objects in the MutableArray Object
and then another method objectAtIndex which iterates the objects at the interval from 0 to (count – 1).
Regards,
Sumit