Access NSMutableArray to an index with no value - iphone

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

Related

how do I get the index at which an Object has been added to an NSMutableArray?

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 .

Getting Index of an Object from NSArray?

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

Find index of an NSArray by passing value

Is it possible in an NSArray to find out if a given value exists or not in the array (without searching it using a for loop)? Any default random method. I went through the documentation, but didn't find much relevant.
Please also tell me about valueForKey method (I was unable to get that from doc).
The containsObject: method will usually give you what you're asking - while its name sounds like you are querying for a specific instance (i.e. two object with the same semantic value would not match) it actually invokes isEqual: on the objects so it is testing by value.
If you want the index of the item, as your title suggests, use indexOfObject:, it also invokes isEqual: to locate the match.
valueForKey: is for when you have an array of dictionaries; it looks up the key in each dictionary and returns and array of the results.
I believe you want to use the indexOfObject method. From the documentation:
indexOfObject:
Returns the lowest index whose
corresponding array value is equal to
a given object.
- (NSUInteger)indexOfObject:(id)anObject
Parameters
anObject
An object.
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.
You can use :
NSInteger idx = [myArray indexOfObject:obj];
to find index of object.
And to check if object is there or not in array you may use :
- (BOOL)containsObject:(id)anObject
Use NSPredicate to filter an NSArray based on NSDictionary
array = [dictionary filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(key == %#)", value]];
if([array count]>0)
{
value exists;
}
Combine objectAtIndex and indexOfObject like this:
[tmpArray objectAtIndex:[tmpArray indexOfObject:yourObject]];

NSIndexPath getIndexes method....how?

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?

Check whether data is present at an index in NSMutableArray

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