NSArray Error: NSCFArray objectAtIndex index (5) beyond bounds (5) - ios

I have an MutableArray filled with values from a database:
NSMutableArray *objectsArray = [[NSMutableArray alloc] init];
for (int n=0; n<[self.array count]; n++) {
[objectsArray addObject:[[self.array objectAtIndex:n] objectForKey:#"Name"]];
[objectsArray addObject:[[self.array objectAtIndex:n] objectForKey:#"Name_En"]];
}
I show the values on labels like so:
cell.textLabel.text = [[[dic objectForKey:#"d"] objectAtIndex:indexPath.row] objectForKey:#"Name"];
cell.detailTextLabel.text = [[[dic objectForKey:#"d"] objectAtIndex:indexPath.row] objectForKey:#"Name_En"];
So far the app works fine. It starts without throwing an exception and the values are in the labels. But if I start to scroll the app crashes and I get the following error:
Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (5) beyond bounds (5)'
Why is this error occurring?

You are probably saying the table that you have 6 rows, but you actually have 5. The reason for this exception is that the table view asks for cell for indexPath.row with value of 5, which means it thinks that there are 6 [0:5] rows, but your array in the dictionary has 5 items [0:5).

I was facing the same the problem which you mention earlier.
Then I did this :-
cell.TitleLabel.text=[[AllUserDataArray objectAtIndex:indexPath.row]objectAtIndex:0];
cell.DateAndTimeLabel.text=[[AllUserDataArray objectAtIndex:indexPath.row]objectAtIndex:1];
cell.InfoLabel.text=[[AllUserDataArray objectAtIndex:indexPath.row]objectAtIndex:2];
if([[AllUserDataArray objectAtIndex:indexPath.row] count] >3) {
NSData *imageData=[[AllUserDataArray objectAtIndex:indexPath.row]objectAtIndex:3];
UIImage *travelImage=[UIImage imageWithData:imageData];
cell.ImgView.image=travelImage;
It is working fine and logically correct also(I think so) :)
Hope this will help you.

I was facing the same the problem and i got the solution:
NSMutableArray *objectsArray = [[NSMutableArray alloc] init];
objectsArray=nil;
for (int n=0; n<[self.array count]; n++) {
[objectsArray addObject:[[self.array objectAtIndex:n] objectForKey:#"Name"]];
[objectsArray addObject:[[self.array objectAtIndex:n] objectForKey:#"Name_En"]];
}

Related

-[__NSArrayM objectAtIndex:]: index 11 beyond bounds [0 .. 10]' objective c

Hi all getting issues with if(indexPath.row==3) section is
-[__NSArrayM objectAtIndex:]: index 11 beyond bounds [0 .. 10]'. Cannot get where the issue is exactly. Below is my code
if(indexPath.row==3)
{
cell.textLabel.text = #"Subject";
cell.detailTextLabel.text=[empDict objectForKey:#"Subject"];
}
if(indexPath.row==3)
{
cell.textLabel.text = #"Education";
cell.detailTextLabel.text=[empDict objectForKey:#"Education"];
}
NSArray *times = [empDict objectForKey:#"ClassTimings"];
NSString *stgmt = [[times objectAtIndex:indexPath.row]objectForKey:#"GMT"];
NSString *strtime = [[times objectAtIndex:indexPath.row]objectForKey:#"Time"];
NSString *strtimeZone = [[times objectAtIndex:indexPath.row]objectForKey:#"TimeZone"];
NSString *str = [#[stgmt, strtime, strtimeZone] componentsJoinedByString:#" "];
if(indexPath.row==3)
{
cell.textLabel.text = #"Times To Take";
cell.detailTextLabel.text=[NSString stringWithFormat:#"%#",str];
}
return cell;
Your problem is not in "if(indexPath.row==3)"
You're getting error from any of bellow three line
NSString *stgmt = [[times objectAtIndex:indexPath.row]objectForKey:#"GMT"];
NSString *strtime = [[times objectAtIndex:indexPath.row]objectForKey:#"Time"];
NSString *strtimeZone = [[times objectAtIndex:indexPath.row]objectForKey:#"TimeZone"];
where you are trying to access 12th element (when value of indexPath.row==12) of the 'times' array which don't have 12 elements...
Hope it helps..
This issue is because you've tried to access 12th element of an array of 11 elements.
In your code, if times array doesn't have 12 elements and if you are trying to access 12th element, this issue can occur. That is if indexpath.row = 12 and you try to access 12th object by [times objectAtIndex:indexPath.row]leads to this error.

Terminating app due to uncaught exception 'NSRangeException', reason

I am using search bar in collection,when I am doing filter text I got the error like
` Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2147483647 beyond bounds [0 .. 37]'
*** First throw call stack:
`
Here is my code
- (void)filterListForSearchText:(NSString *)searchText
{
for (NSString *title in _arrayCCName) {
NSRange nameRange = [title rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (nameRange.location != NSNotFound) {
[_searchResultName addObject:title];
}
}
for (int i=0; i<_searchResultName.count; i++) {
NSString *str=[ObjCls objectAtIndex:i];
NSInteger index=[_searchResultName indexOfObject:str];
[_searchResultDeignation addObject:[_arrayCCDesignation objectAtIndex:index]];
[_searchResultProfilePicture addObject:[_arrayCCProfilePicture objectAtIndex:index]];
[_searchResultFamilyPicture addObject:[_arrayCCFamilyPicture objectAtIndex:index]];
NSLog(#"array index is %ld",(long)index);
}
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
SEARCHBAR.showsCancelButton=NO;
[self.view endEditing:YES];
}
I got above error please help me how it is solve?
Simply means that the value of index is greater than the size of array at some point. When using [array objecAtIndex:index], index must be less than array.count.
These lines here....
NSInteger index=[_searchResultName indexOfObject:str];
[_searchResultDeignation addObject:[_arrayCCDesignation objectAtIndex:index]];
[_searchResultProfilePicture addObject:[_arrayCCProfilePicture objectAtIndex:index]];
[_searchResultFamilyPicture addObject:[_arrayCCFamilyPicture objectAtIndex:index]];
NSLog(#"array index is %ld",(long)index);
You are assuming that the indexOfObject actually finds something. What happens if the str doesn't exist
Taken from the documentation....
Declaration
OBJECTIVE-C
- (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.

why iOS App terminating due to NSRangeException

I'm having a weird error popping up. It's listing that my app is
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
What puzzles me is that the app runs perfectly fine in the simulator, but when I go to test it on my device I get that error. I've isolated the problem to the line of code below:
updatingTracker = [userDatas objectAtIndex:repeatCount];
Here is the rest of the relevant code:
[self getUserDatas];
[self timerDidFire];
-(void) getUserDatas
{
userDatas = [[NSMutableArray alloc] init];
NSUserDefaults *userdef = [NSUserDefaults standardUserDefaults];
int count = [[userdef objectForKey:#"user_count"] intValue];
for(int i=0;i<count;i++)
{
NewTracker *newtrack=[[NewTracker alloc] init];
newtrack.FromCurrency = [userdef objectForKey:[NSString stringWithFormat:#"from_string_%d",i]];
newtrack.ToCurrency = [userdef objectForKey:[NSString stringWithFormat:#"to_string_%d",i]];
newtrack.savedCurrency = [userdef objectForKey:[NSString stringWithFormat:#"save_currency_%d",i]];
newtrack.userTarget = [userdef objectForKey:[NSString stringWithFormat:#"user_target_%d",i]];
newtrack.trackerId = [userdef objectForKey:[NSString stringWithFormat:#"tracker_id_%d",i]];
newtrack.realtimeBase = [userdef objectForKey:[NSString stringWithFormat:#"realtime_base_%d",i]];
newtrack.realtimeTarget = [userdef objectForKey:[NSString stringWithFormat:#"realtime_target_%d",i]];
newtrack.realtimeUSD = [userdef objectForKey:[NSString stringWithFormat:#"realtime_USD_%d",i]];
[userDatas addObject:newtrack];
}
}
- (void) timerDidFire
{
NSLog(#"bug finder");
updatingTracker = [userDatas objectAtIndex:repeatCount];
[self chartconnectionStart:#"3m"];
}
Any ideas or help on why this is happening or how to fix it would be appreciated.
Your userDatas array is empty. You most likely don't have anything populated in your user defaults on your phone, so the code that adds to the array is never executed. You probably have some data already populated on your simulator and that's why it's not working on the phone
Simple put a conditional breakpoint on that line for the condition [userDatas count] == 0. Or put in an if to catch that and a breakpoint on it. They use the debugger to figure out how you got there and what the associated values are.
Basic debugging.
Code like this
(void) timerDidFire{
NSLog(#"bug finder");
if([userDatas count]>0){
updatingTracker = [userDatas objectAtIndex:repeatCount];
[self chartconnectionStart:#"3m"];
}
}
Happy coding..........

Looping through an array, index error

I am creating a UIScrollView that scrolls sideways and has a number of buttons and labels (that go with the buttons) that I am adding programmatically.
I have 44 buttons and labels, so I want to create them through an array.
This is how I am trying to do it (I'm a newish programmer so I know for a fact its the wrong way to do it.
Keep in mind, nameArray holds strings for the labels and the picArray holds strings for the filenames for pictures.
Anyways, this is in my viewDidLoad::
for (int i = 0; i < 44; i++) {
NSIndexPath *path = [nameArray objectAtIndex:i];
[self makeLabelsAndButtons:path];
//NSLog(#"index path is:%#", path);
}
The method that this for loop is referencing is written below:
-(void)makeLabelsAndButtons:(NSIndexPath*)indexPath{
NSString *nameString = [nameArray objectAtIndex:indexPath];
NSString *picString = [picArray objectAtIndex:indexPath];
NSLog(#"name: %#, pic:%#", nameString, picString);
}
There is not much in the makeLabelsAndButtons method because I am trying to get the concept down before adding the meat of the code.
This is the error I crash with:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 54564 beyond bounds [0 .. 43]
I know that this means the array is out of the bounds but I have no idea why.
Any help is appreciated!
If nameArray holds strings for the labels, then path is not an NSIndexPath, it's a string. So you're passing a string to objectAtIndex: which, of course wants an integer not a string.
Even if it were an NSIndexPath, your code would still be wrong because you want an integer not an index path to pass to objectAtIndex.
I think what you want to do is just pass i to your makeLabelsAndButtons method.
for (int i = 0; i < 44; i++) {
[self makeLabelsAndButtons:i];
//NSLog(#"index path is:%#", path);
}
-(void)makeLabelsAndButtons:(NSInteger)index{
NSString *nameString = [nameArray objectAtIndex:index];
NSString *picString = [picArray objectAtIndex:index];
NSLog(#"name: %#, pic:%#", nameString, picString);
}
Try like this...
either this...
for (int i = 0; i < [nameArray count]; i++) {
NSIndexPath *path = [nameArray objectAtIndex:i];
[self makeLabelsAndButtons:path];
}
or like this...
for (NSIndexPath *path in nameArray) {
[self makeLabelsAndButtons:path];
}

tableView crashes when adding the first item (and also when deleting last item)

After cleaning up my code and making it ready for deployment I encountered a weird problem. When I try to add a contact to my tableview it always crashes when the empty is array. After that its not problem to add as many as you want. And also when I delete a contact and the array is empty, it also crashes with the same error message:
Terminating app due to uncaught exception 'NSRangeException', reason:
' -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
Here is what I do: I add a contact via php to my database, read it out with xml and give it back to the app so the user can instantly see what happened (adding a contact that is). There is a lot of code involved so I stick to the basics for now.
When the view loads the array gets allocated. User can add a contact. While adding the contact a php file is called that creates the xml file where the contacts are saved.
Here is where I get the object back and paste it into my array and display it
self.filteredListContent = [NSMutableArray arrayWithCapacity:[self.tabelle count]];
self.tableView.scrollEnabled = YES;
numbers = [[NSMutableArray alloc] init];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *fileName = [prefs stringForKey:#"number"];
NSString *cc = [prefs stringForKey:#"Code"];
NSString *urlString = [NSString stringWithFormat: #"http://myserver/%#%#.xml", cc, fileName];
NSURL *url = [NSURL URLWithString: urlString];
DataFileToObjectParser *myParser = [[DataFileToObjectParser alloc] parseXMLAtUrl:url toObject:#"contacts" parseError:nil];
for(int i = 0; i < [[myParser items] count]; i++) {
contacts *new = [[Telefonbuch alloc] init];
new = (contacts *) [[myParser items] objectAtIndex:i];
[numbers addObject:new];
[self.tableView reloadData];
And here is how it gets displayed, nothing special:
NSString *TableText = [[NSString alloc] initWithFormat:#"%#", [[numbers objectAtIndex:indexPath.row] fname]];
NSString *TableText2 = [[NSString alloc] initWithFormat:#"%#", [[numbers objectAtIndex:indexPath.row] lname]];
NSString *cellValue = [NSString stringWithFormat:#"%# %#", TableText, TableText2];
cell.textLabel.text = cellValue;
Your loop sounds strange.
for(int i = 0; i < [[myParser items] count]; i++) {
contacts *new = [[Telefonbuch alloc] init];
new = (contacts *) [[myParser items] objectAtIndex:i];
[numbers addObject:new];
[self.tableView reloadData];
First avoid to use new keyword (as user1118321 already suggested).
Then, what is contacts? Is contacts a superclass of type Telefonbuch?
What do these two lines mean?
contacts *new = [[Telefonbuch alloc] init];
new = (contacts *) [[myParser items] objectAtIndex:i];
You alloc-init an instance of Telefonbuch class to a new (avoid this) variable but then you assign that variable to another object. Why?
The right code could be like the following.
for(int i = 0; i < [[myParser items] count]; i++) {
Telefonbuch* newContact = (Telefonbuch*) [[myParser items] objectAtIndex:i]; // or contacts* newContact = (contacts*) [[myParser items] objectAtIndex:i];
// maybe it could be better to rename contacts with a capital letter
[numbers addObject:newContact];
}
[self.tableView reloadData];
Some notes
If you want to add or delete item to a table view, you need to do it in 2 stages:
1) Deal with your model
[yourModel removeObjectAtIndex:row];
2) Deal with your table’s animation
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
If you need to download content, maybe you could consider to do it asynchrously without blocking the main thread. In particular, this is could be the synchronous call that could be a blocking one (since I don't have any details I'm only supposing it).
DataFileToObjectParser *myParser = [[DataFileToObjectParser alloc] parseXMLAtUrl:url toObject:#"contacts" parseError:nil];
If you don't use ARC, pay attention to memory management.
Hope it helps.

Resources