NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 5 beyond bounds for empty array' - ios

in my application when i run app for first time,it work ok.but when i run again 2 two times, it crashes.
This is the error..
NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 5 beyond bounds for empty array'

Reason: You are accessing Empty array about to access object at index.
replace all places like in your code below
[arrMydata objectAtIndex:indexPath.row];
with
//1. Positive index ([anArray objectAtIndex:-NUMBERS]) will crash
//2. within the array boundary
if([arrMydata count] > 0 && [arrMydata count] > indexPath.row){
shrObj=[arrMydata objectAtIndex:indexPath.row];
}
else{
//Array is empty,handle as you needed
}
**Here You can see the non software example, which will explain this issue. Good luck! **

You array is empty, but you're trying to access an object in it. That is the problem.

Reason: According to your log, you're trying to access empty array. Just fix this by below code
if (arrMydata.count > inxexPath.row)
sharObj = [arrMydata objectAtIndex:indexPath.row]

In case this helps someone : in my case the array was not in code, but an IB outlet that was an array of 5 UIImageViews in the storyboard.
#IBOutlet var upAndDownArrowImages: [UIImageView]!
Reason for the crash was that I mistakenly deleted 1 of those UIImageViews from the Storyboard.

In my case, it Crashes for heightForRowAt indexpath, Do check this method for smooth operation.
Hope it Helps someone.

Related

'NSRangeException', reason: '*** -[__NSArrayM objectAtIndexedSubscript:]: index 1 beyond bounds [0 .. 0]'

I've added exception breakpoints and it always blows up on this line
BookPage *page = _sections[path.section].pages[path.row];
Bare in mind I'm new in objective-c
Any help would be appreciated.
In this code have two places where this Exception one is _sections[path.section] and another is the full code.
First check the _sections contains the pages array of that position path.section. If contains then check count the pages count and then try to get the row value.
Like this:
if ([_sections count] > path.section){
if ([_sections[path.section].pages count] > path.row){
BookPage *page = _sections[path.section].pages[path.row];
}
}
Hope this will fix your problem.

Swift 3 range exception?

let x = self.tableProduct.count
self.tableProduct = products
self.tableView.beginUpdates()
var insertedIndexPaths = [IndexPath]()
for i in x..<self.tableProduct.count {
print("No : \(i)")
insertedIndexPaths.append(IndexPath(row: i, section: 0))
}
print("Count = \(self.tableProduct.count)")
print(insertedIndexPaths)
self.tableView.insertRows(at: insertedIndexPaths, with: .none)
self.tableView.endUpdates()
Here x is the current array count. Since I'm fetching in background after assigning I update array in second line. Then I start updating table view. Lets say initially my table has 50 records that is x, then I want to add row from 51 to self.tableProduct.count which is 100. In for loop I add index path my first index path is [0,51] and last index path looks like [0,99]. Then I start to insert my new rows, here it throws
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 17 beyond bounds [0 .. 16]'
error.When I add breakpoint to error it shows error in tableView.endUpdates() line.Here what I'm doing wrong? How can I solve this error? Thanks in advance.

Seemingly random indexes causes out of bounds error when referencing a cell in a table view

I'm not sure if I'm missing something very basic or if this is just another problem I've run into with Swift UITableviews. My problem is that I reference a cell in the table view (in this case section 4 row 0) and for some reason swift is giving me an out of bounds error with an index (6) that shouldn't ever exists because the size of the section should only be 4 the log also never showed a 5 (when printing positionCounter in the while loop). Any help would be greatly appreciated I have no idea why I would be getting a value of 6 in this instance please let me know if you need me to provide any extra code or clarify anything.
Error Message
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 6 beyond bounds [0 .. 5]'
The code surrounding the error
cell = tableView.dequeueReusableCell(withIdentifier: "Item Card", for: indexPath)
var positionCounter = 0
while positionCounter < eventSettingsTableView.numberOfRows(inSection: 4) {
print(positionCounter)
print(String(eventSettingsTableView.numberOfSections) + " NUMBER OF SECTIONS")
print(String(eventSettingsTableView.numberOfRows(inSection: 4)) + " NUMBER OF ROW IN SECTION 4")
if eventSettingsTableView.cellForRow(at: IndexPath(row: 0, section: 4)) != nil {
print("no")
} else {
print("yes")
}
positionCounter = positionCounter + 1
}
positionCounter = 0
I have narrowed the error down to this line (changing the section from 4 to 3 fixes the error but doesn't explain why positionCounter was ever 6)
if eventSettingsTableView.cellForRow(at: IndexPath(row: 0, section: 4)) != nil {
EDIT - Sorry forgot to mention that this code is located in the cellForRowAt function for my UITableView
It appears that you are calling cellForRowAt: from within cellForRowAt:. This is going to cause issues depending on the situation. You might want to look at implementing the following logic differently:
if eventSettingsTableView.cellForRow(at: IndexPath(row: 0, section: 4)) != nil {
print("no")
} else {
print("yes")
}
Update:
As #PaulW11 points out, calling the tableview's cellForRowAt: from within the data source cellForRowAt: should not be an issue. And he's right.
However, I set up a demo project to investigate the issue and removing the call to cellForRowAt: but retaining the loop results in the crash not occurring. Additionally, I set up a static array of data and noticed that the crash was not due to a boundary condition either since while the array was 9 items long, I got out of bounds issues indicating that iOS was looking at a 12 item array where the access seemed to be for the 13th item :)
So, at the moment, my suspicion is that this issue is due to some sort of timing/race condition where cellForRowAt: is called multiple times within a loop and something goes wonky. But what that "something" is, I don't know. If somebody has any ideas, I'd be really interested to hear about it since this is an interesting question ...

NSRangeException when change dataSource

I have UITableView which dataSource change by selecting UISegmentControl's segment. It has only 2 segments and for both states I load data asynchronously first time into 2 different arrays "firstTypeNotificationsArray" and "secondTypeNotificationsArray". The main array is dataSource for UITableVIew which has data from one of arrays each time and it named "allNotificationsArray".
Change main dataSource data method
-(void)changeNotificationsByType:(BOOL)firstType{
[allNotificationsArray removeAllObjects];
if(firstType){
[allNotificationsArray addObjectsFromArray:firstTypeNotificationsArray];
} else {
[allNotificationsArray addObjectsFromArray:secondTypeNotificationsArray];
}
[notificationsTable reloadSections:[NSIndexSet indexSetWithIndex:0]
withRowAnimation:UITableViewRowAnimationFade];
}
Before call method changeNotificationsByType I check my arrays count to be !=0 but I get an NSRangeException after calling.
numberOfRowsInSection method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return allNotificationsArray.count;
}
I tried to call reloadSections in main thread with dispatch_async but it didn't help. I've also tried to do reloadData instead and no result.
Here is a crash log:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 60 beyond bounds [0 .. 0]'
*** First throw call stack:
(0x265ec87b 0x3832adff 0x26502633 0xfcb9f 0x196879 0x3ee4a5 0x1a9dd17 0x1a9dd03 0x1aa27c9 0x265af555 0x265ada4f 0x26500129 0x264fff1d 0x2fac7af9 0x2a9889bd 0x10cc6d 0x38a78873)
libc++abi.dylib: terminating with uncaught exception of type NSException
This crash raise after switching UISegmentControl and calling changeNotificationsByType respectively. All arrays are not empty at this moment and I can't understand why my app is crashing.

NSRangeException - NSArrayM objectAtIndex

EDIT - SOLVED: the problem was when I created the string with all the objects to put into the tableview. I used the '?' to separe each object and one of those contained that character so the array broke.
[myString appendFormat:#"%#$%#$%#$%#?",
[currentCampeggioDict valueForKey:#"id"],
[currentCampeggioDict valueForKey:#"nome"], [...]
NS Array *elencoCampeggi=[myString componentsSeparatedByString:#"?"];
That's it.
I have this problem: my app receives from an URL a XML file with a list of objects. The tableview is populated by those objects. There are so many items, so I have to call several times the url, changing a parameter in it for example :
http://www.myurl.com?method=xxx&PAGE=1
http://www.myurl.com?method=xxx&PAGE=2
etc..
The last cell of the tableview contains the sentence "Click to load next 25 objects" and it changes the page number for the URL, delete itself and reload the url, adding the new objects to the tableview.
After 4 times everything works great, but when I press the cell for the fifth, an exception appears with the following text:
Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 17 beyond bounds [0 .. 16]'
Any help? Thanks.
EDIT: some code: this is the part where I delete the last cell
-(void) loadTestData {
// fill moviesArray with test data
NSInteger lastRow = [CampeggiArray count]-1;
if (lastLoadedPage > 1){
[CampeggiArray removeObjectAtIndex:lastRow];
[self.tableView reloadData];
}
[...]
Issue is because you are returning wrong row count in your tableview delegate method. You need to identify the total no of objects to be listed in the tableview and return the count in your tableview delegate method. This is not your page size.
For each hit you need to keep on appending the new objects to the already existing datasource(NSArray) and reload the table.There will be no objects in the datasource during initial hit.
I guess, you are returning 16 instead of 15 in the delegate method, so you wil get crash with exception. Don't hard code values in your delegate method, just get the total number of objects(entire set) and return the count of it.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [totalObjects count];
}

Resources