Testing for contents of an NSArray without risking range error - iphone

I'm foolishly saying:
if ([imageCache objectAtIndex:index]) {
Problem is, on my first time through this, I haven't put ANYTHING in my NSMutableArray *imageCache, and this croaks with a range error.
How can I ask an NSMutableArray whether it has anything for a particular index?

The NSArray cluster class cannot store nil. So I think it is sufficient to simply check the bounds:
NSUInteger index = xyz;
if (index < [imageCache count]) {
id myObject = [imageCache objectAtIndex:index];
}

What I find really useful is having a safeObjectAtIndex: method. This will do the check for you and will return nil if the index is out of range.
Just create a new category on NSArray and include the following methods:
- (id)safeObjectAtIndex:(NSUInteger)index;
{
return ([self arrayContainsIndex:index] ? [self objectAtIndex:index] : nil);
}
- (BOOL)arrayContainsIndex:(NSUInteger)index;
{
return NSLocationInRange(index, NSMakeRange(0, [self count]));
}

if (index < [imageCache count])
...

This code answers your question. Unlike the accepted answer, this code handles passing in a negative index value.
if (!NSLocationInRange(index, NSMakeRange(0, [imageCache count]))) {
// Index does not exist
} else {
// Index exists
}

[imageCache count] will return the number of items in your array. Take it from there :-)

Check the number of items in the array first with [imageCache count]. Don't try to ask for anything with an index greater than that result.

Related

Object at index in NSArray

I have an array. I want to check whether there is an object present in a particular index or not. How to do this? Please help.
if you just want to check if there is an object
if (myIndex < [array count])
if you want to find a specific object
[array indexOfObject:myObject];
if you want to know if the object at some index is of some class
[[array objectAtIndex:myIndex] isKindOfClass:[TheClassToCompareTo class]];
BOOL exists = index < [array count] ? YES : NO;
You can use containsObject method to check weather your array contains the specific object or not. If contains, then get its index by indexOfObject method
if ([yourArrayArray containsObject:yourObject])
{
NSLog(#"Found");
int index = [yourArray indexOfObject:yourObject];
}
I know this is old thread but just trying to help.
You can add a category to NSArray something like this
#implementation NSArray (Safe)
- (id)safeObjectAtIndex:(NSUInteger)index {
if (index >= [self count]) return nil;
return [self objectAtIndex:index];
}
#end
You should check the length of the array (using the count method) and given NSArray cannot contain nil it must therefore contain something:
- (BOOL)arrayContainsSomethingAtIndex:(NSUInteger) index
{
return [_myArray count] > index;
}
Use indexOfObject: method.
if ([Array indexOfObject:object]==index) {
//code
}
check like this
if([array objectAtIndex:i]!= nil)
{
NSLog("Object present");
}
else{
NSLog("Object Not Present")
}
Modified:
You should make like this
if(i<=[array count]){
if([array objectAtIndex:i]!= nil)
{
NSLog("Object present");
}
else{
NSLog("Object Not Present")
}
}
This will not raise exception and object in array should compare with nil value
First you must check if the index of that object is smaller than the size of the array, then you query the array at that index.
if (index < [array count] && [array objetAtIndex:index]){
/* Your code*/
}

What is error in this code?

for(NSDictionary *feed in Feeds)
{
NSString *feedName=[feed objectForKey:#"name"];
if(listofBusiness==nil)
{
listofBusiness=[[NSMutableArray alloc]init];
}
if([listofBusiness indexOfObject:feedName] !=NSNotFound)
{
[listofBusiness addObject:feedName];
[feedName release];
feedName=nil;
}
}
in this code when compiler comes on this statement
if([listofBusiness indexOfObject:feedName] !=NSNotFound)
then not go into codition and go to increment in for loop so that any element is not added in array.what is error in this code?
The logic appears to be inverted - you probably want it to add the elemement when
[listofBusiness indexOfObject:feedName] == NSNotFound
But at the moment you have the opposite - you only try to add the object when it is 'not not found' - i.e. when it is already present in the list.
indexOfObject is not working for an array
Try with containsObject method of an array.
Example :
if([listofBusiness containsObject:feedName]) {
// your code
}

Objective-C: using if/else statement with Plist values

I'm sure this is really basic but I can't see what I'm doing wrong. Can someone help me understand where I'm going wrong please? I'm working in xcode. I'm trying to make different parts of my view appear depending on values saved in a property list. If the value assigned to a particular UITextField is equal to zero then I want to hide that UITextField. I'm trying to do this like this. gross is the name of a UITextField:
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
gross.text = [array objectAtIndex:7];
if ([array objectAtIndex:7 == 0]) {
gross.hidden = YES;
}
else {
gross.hidden = NO;
}
[array release];
I think the problem is something to do with how I've wrote the if/else statement. I know this is really basic but I don't quite understand where I'm going wrong. So Your help is much appreciated.
Code should read:
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
gross.text = [array objectAtIndex:7];
if ([[array objectAtIndex:7] isEqualToString:#"0"]) {
gross.hidden = YES;
} else {
gross.hidden = NO;
}
[array release];
This assumes that the object at index 7 of your array exists and is a string. If it's actually an NSNumber, then you should instead use the conditional
if ([[array objectAtIndex:7] intValue] == 0) {
Note the above line works for a string where the text contains an int, such as #"0" or #"7".
if ([[array objectAtIndex:7] intValue] == 0)
First mistake is position of closing ]. And second one is you probably have NSString in array, as you have assigned that in text property. So you need to convert it to int by using intValue.
If your array contains nsstring then your condition should look like:
if ([[array objectAtIndex:7] intValue] == 0) {
...
or
if ([[array objectAtIndex:7] isEqualToString:#"0"]) {
1st condition will work also if your array contains NSNumbers (not likely in your case as you assign array elements to text property), but will fail if string is not a valid number - in that case intValue will return 0 as well.
2nd condition will work fine if you're sure that your elements are strings and you want to compare exactly with #"0".
Your condition is equivalent to
if ([array objectAtIndex:0])
because == operator has greater priority and evaluates to 0. Comparing array's element to 0 directly also does not make sense as NSArray cannot contain nil objects anyway
It might be easier to get the length of the array first and make sure that it has enough elements and then start accessing the elements themselves.

How to determine the index number of the last object in a NSMutable Array

I have a NSMutable Array and was trying to find the index number of the last object in this array. I tried this, but it feels cumbersome:
int currentCount = [[[self.myLibrary objectAtIndex:currentNoteBookNumber] tabColours] count];
NSLog(#"Number of tab colours total: %i", currentCount);
NSLog(#"Index number of last object: %i", currentCount-1);
Is there another way of doing this? The context of my problem is that I need to determine the last object in order to change it:
replaceObjectAtIndex:[last object] withObject: ...
Thanks!
If you need the index, then that is the way to do it (int lastIndex = [array count] - 1;). If you just want to replace the last object with a different object however, you can do:
[array removeLastObject];
[array addObject: newLastObject];
Try this:
[myArray replaceObjectAtIndex:[myArray count]-1 withObject:someNewObject];
If you add objects to your NSMutableArray with addObjects: method it always put elements at the end. When you removeObjectAtIndex:index it automatically shift down on 1 position all elements with indexes > index. That is why the last object in array is always have index [array count] - 1. I do not tell you about replacing objects, I just tell about adding objects.
int index=[*yourarrayname* indexOfObject:[*yourarrayname* lastObject]];
NSLog(#"index=%d",index);
Use this snippet:
int lastIndex = [YOUR_ARRAY count] - 1;
this will gives you last index of your array.

NSMutable Array

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...
}