I'm writing a program that contains an array with multiple objects inside it. Then, I take specific objects from that array and store their indexes (from array1) in another array as NSNumbers. Now, I'm trying to reference the objects from array1 later on in the project by pulling the indexes out of array2 in a table view, but I keep getting an error that suggests that I'm getting the objects' memory addresses instead of the object itself. Code to follow:
self.indexArray = [NSMutableArray new];
for (Item *item in array1){
if (item.ID == comparedItem.ID){
NSUInteger num = [array1 indexOfObject:item];
NSNumber *numval = [NSNumber numberWithInteger:num];
[self.indexArray addObject:numval];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = (EditItemTableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"quantityCell"];
int indexNum = [[self.indexArray objectAtIndex:(indexPath.row-1)] intValue];
NSString *descString = [NSString stringWithFormat:#"%# %# - %#",[[array1 objectAtIndex:indexNum]desc1],[[array1 objectAtIndex:indexNum]desc2],indexNum];
return cell;
}
So I'm getting an error on the line: int indexNum = [[self.indexArray objectAtIndex:(indexPath.row-1)] intValue]; that usually reads something like this: *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 4294967295 beyond bounds [0 .. 2]'. This is assuming I added 3 objects to the array before running the code above (hence the 0 .. 2). I'm assuming that 4294967295 is a memory address. Does anybody have any idea about how I can get the object itself instead?
Thank you!
4294967295 is -1 represented as an unsigned int32. In this context, it represents indexPath.row-1 == -1 or indexPath.row == 0.
I'm not sure why you're subtracting 1 from your indexPath.row, but you should add some safety to check the bounds to make sure your array lookup won't be fetching an element that's out of bounds.
if (indexPath.row == 0) // do something special
or
[self.indexArray objectAtIndex:indexPath.row]
Related
Here is some of my code
NSArray *selectedRows = [self.playHistoryTableView indexPathsForSelectedRows];
if (selectedRows.count) {
for (NSIndexPath *selectionIndex in selectedRows)
{
OneSery *sery = [self.playHistoryDic objectAtIndex:selectionIndex.row];
[CoreDataManager deleteOneHistoryBySeryId:sery.seryId andVideoId:sery.latestVideo.videoId];
[self.playHistoryDic removeObjectAtIndex:selectionIndex.row];
}
[self.playHistoryTableView deleteRowsAtIndexPaths:selectedRows withRowAnimation:UITableViewRowAnimationAutomatic];
}
When select the cells one at a time, it works well. But when multiselect the cell it gonna to crash like this:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
I know what it mean but I have no idea where I am wrong. And I tried, when it had three cells and I select the first and second to delete, it delete the first and third cell. When it had only two cells, I select both of them to delete, it does crash my app.
When I debug it, even the Onesery *sery value is wrong. So, how could selectionIndex is wrong while selectedRows is right?
Great thanks to #Wain it's finally done with those:
NSArray *selectedRows = [self.playHistoryTableView indexPathsForSelectedRows];
NSMutableIndexSet *indicesOfItemsToDelete = [[NSMutableIndexSet alloc] init];
if (selectedRows.count) {
for (NSIndexPath *selectionIndex in selectedRows)
{
OneSery *sery = [self.playHistoryDic objectAtIndex:selectionIndex.row];
[CoreDataManager deleteOneHistoryBySeryId:sery.seryId andVideoId:sery.latestVideo.videoId];
[indicesOfItemsToDelete addIndex:selectionIndex.row];
}
[self.playHistoryDic removeObjectsAtIndexes:indicesOfItemsToDelete];
[self.playHistoryTableView deleteRowsAtIndexPaths:selectedRows withRowAnimation:UITableViewRowAnimationAutomatic];
}
In your loop you're doing
[self.playHistoryDic removeObjectAtIndex:selectionIndex.row];
so you're changing the list of items. On each iteration you try to access an item, but after the first item the next one has moved, because you removed one. For each subsequent item this is worse.
Eventually you get to a point where you try to access an item but so many have been removed that you go past the end of the list, then you crash.
You should get an array of the items to be removed in your loop and remove them all at once after the loop has completed.
I keep getting the following error when trying to insert a row:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]'
*** First throw call stack:
(0x31fe82a3 0x39ccc97f 0x31f33b75 0x8d18f 0x33fee5a9 0x33edb0c5 0x33edb077 0x33edb055 0x33eda90b 0x33edae01 0x33df9421 0x31fbd6cd 0x31fbb9c1 0x31fbbd17 0x31f2eebd 0x31f2ed49 0x35af62eb 0x33e44301 0xa49d 0x3a103b20)
libc++abi.dylib: terminate called throwing an exception
Does anyone know what's going on here?
Here is my code:
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if(editingStyle == UITableViewCellEditingStyleDelete)
{
Caseload *deletedCaseload = [self.caseload objectAtIndex:indexPath.row];
[self.caseload removeObject:deletedCaseload];
[self.caseloadTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
else if
(editingStyle == UITableViewCellEditingStyleInsert)
{
Caseload *copiedEntry = [self.caseload objectAtIndex:indexPath.row];
Caseload *newEntry = [[Caseload alloc]init];
newEntry.name = copiedEntry.name;
newEntry.address = copiedEntry.address;
newEntry.phoneNumber = copiedEntry.phoneNumber;
newEntry.identNumber = copiedEntry.identNumber;
[self.caseload addObject:newEntry];
[self.caseloadTableView insertRowsAtIndexPaths:
[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationRight];
}
}
This types of error generate whenever you try to get object/value of an array at totalIndex + 1 such like for example if your array has 4 value (Make sure index start with 0) and you try to fetch value such like
[Myarray objectAtIndex:4] at that time this type of error occur.
So best why is use breakPoint and find out your problem by help of my suggestion.
The error is "NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]'". That means you're calling "objectAtIndex:" somewhere with an index of 2, and your NSArray only has entries at index 0 and index 1.
You need to figure out where you are setting the bogus index, which I suspect might start in your "numberOfRowsInSection:" method.
I was trying to insert items into a collection view with this code:
- (IBAction)addCards:(UIButton *)sender {
int numberOfCardsToAdd = EXTRA_CARDS_NUMBER;
if ([[self.collectionView visibleCells] count] == 0) {
numberOfCardsToAdd = self.startingCardCount;}
// loop through the game model, draw random cards from the deck and assign it to the array
// take into account the "no cards left in deck" case
for (int i = 0; i < numberOfCardsToAdd; i++) {
if (![self.game.deck isEmpty]) {
SetsCard *cardToAdd = (SetsCard *) [self.game.deck drawRandomCard];
if (cardToAdd) [self.game.cards addObject:cardToAdd];
NSIndexPath *newObject = [[NSIndexPath alloc] initWithIndex:[self.game.cards indexOfObject:cardToAdd]];
[self.collectionView insertItemsAtIndexPaths:#[newObject]]; // adding card to view
}
}
[self.collectionView reloadData];
}
and I got this error:
Assertion failure in -[NSIndexPath row], /SourceCache/UIKit_Sim/UIKit-2380.17/UITableViewSupport.m:2680
2013-06-13 09:09:12.443 Improved Matchismo[1206:c07] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid index path for use with UITableView. Index paths passed to table view must contain exactly two indices specifying the section and row. Please use the category on NSIndexPath in UITableView.h if possible.'
*** First throw call stack:
(0x1cb1012 0x10eee7e 0x1cb0e78 0xb84665 0x29eb6c 0x54b14d 0x53fd69 0x53e60e 0x53e646 0x926e 0x1102705 0x362c0 0x36258 0xf7021 0xf757f 0xf66e8 0x65cef 0x65f02 0x43d4a 0x35698 0x1c0cdf9 0x1c0cad0 0x1c26bf5 0x1c26962 0x1c57bb6 0x1c56f44 0x1c56e1b 0x1c0b7e3 0x1c0b668 0x32ffc 0x269d 0x25c5)
libc++abi.dylib: terminate called throwing an exception
which really confuses me because I was adding items to an UICollectionView, not an UITableView, and my app does not use any instance of UITableView at all. Does anyone know why I got this error, and how I can fix it?
Thanks very much in advance!
A collection view works with two-level index paths (section/row) in the same way as
a table view, so you should create the index path
NSIndexPath *newObject = [NSIndexPath indexPathForRow:... inSection:0];
if there is only one section (section 0).
-[NSIndexPath row] is declared in the #interface NSIndexPath (UITableView) category and the error message has probably not been changed when collection views were introduced in iOS 6, so the message "Invalid index path for use with UITableView" is misleading.
When I run the search function in aepub reader my app crashes. It enters the cellfor row at index method and when it executes NSLOg(#"%#",hit.neighbourText) it shows exception.
(UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.adjustsFontSizeToFitWidth = YES;
NSLog(#"indexpath%d",indexPath.row);
NSLog(#"%#",[results objectAtIndex:[indexPath row]]);
hit = (SearchResult*)[results objectAtIndex:[indexPath row]];
if([results count]>0) {
NSLog(#"%#",hit.neighboringText);
cell.textLabel.text = [NSString stringWithFormat:#"...%#...", hit.neighboringText];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Chapter %d - page %d", hit.chapterIndex, hit.pageIndex+1];
return cell;
}
}
I am getting some value for hit.neighboringText but after that, I reload my tableview then the following exception will be raised, why?
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString
neighboringText]: unrecognized selector sent to instance 0x1481c4'
*** First throw call stack:
It's because hit is actually an NSString object and not a SearchResult object as you expect:
hit = (SearchResult*)[results objectAtIndex:[indexPath row]];
The clue is in the exception text:
-[__NSCFConstantString neighboringText]: unrecognized selector sent to instance ...
^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
No amount of casting to SearchResult is going to change that.
EDIT: Actually anywhere you see a cast you should be suspicious of the actual object you are dealing with. If you aren't sure then check it with isKindOfClass:.
it means that hit = (SearchResult*)[results objectAtIndex:[indexPath row]]; returns a ConstantString and not SearchResult object
Best would be checking if hit is the same class type as SearchResult before getting the value from neighboringText
you can try like something like this:
if([hit isKindOfClass:[SearchResult Class]]){
// do something with hit
}
else{
// different class
}
The answer to your problem lies in the error message:
unrecognised selector sent to instance 0x1481c4.
What you need to do next is print the value of that address via po 0x1481c4. It would appear that it is not actually a string, but you are not showing that code.
I guess there are two possibilities:
hit is not a SearchResult object but a String object
hit or the results array is not owned anymore / released but not set to nil and point garbage, which I believe is the case because I have experienced it before
I think you need to make sure that the array is not autoreleased/released at that point (for example if you are creating it with [NSArray arrayWith...] it is autoreleased, you might not own it inside cellForRowAtIndexPath) and the hit object is properly initialized before giving it to the results array.
In my application I try to load contents from a url, store them in a mutable array and show them in a table view. But I can't get it working, because every time I run the app this error appears:
*** Terminating app due to uncaught exception 'NSRangeException',
reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
*** First throw call stack:
(0x34dd088f 0x36d9e259 0x34d2823d 0x316e562f 0x315f09a9 0x313c0c5d 0x313c1b95 0x313c1ae7
0x313c16c3 0xa5cfb 0x33623ec7 0x35387a09 0x35390051 0x33622965 0xa4dc1 0x313a8e33
0x313cd629 0x31391d7d 0x314544dd 0x3139a55d 0x3139a579 0x3139a40b 0x3139a3e7 0x313a8015
0x313a1985 0x3136fc6b 0x3136f70f 0x3136f0e3 0x3439222b 0x34da4523 0x34da44c5 0x34da3313
0x34d264a5 0x34d2636d 0x313a0a13 0x3139de7d 0xa4745 0xa46dc)
terminate called throwing an exception
I create the array that should populate the table in my viewDidLoad with:
_videos = [[NSMutableArray alloc] init];
Then I connect to the url and parse through the received xml data. This works just like it should. When a certain tag is opened I create my video objects and after filling them with data I add those objects to my array with:
[_videos addObject:currentVideo];
This seems to work as well, because it returns the correct number of videos when
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _videos.count;
}
is called. But after this point the app crashes and I don't even reach the point where I try to populate my table view. The function looks like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Video *curVideo = [_videos objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.titleLabel.text = [curVideo title];
cell.descLabel.text = [curVideo desc];
return cell;
}
What am doing wrong?
Thanks in advance
I had the same error signature -[__NSArrayI objectAtIndex:]: index 4 beyond bounds [0 .. 1]' when attempting to present a modal Storyboard, table view with two (updated from five) static table cell sections. This error didn't come up until I removed three table cell sections I no longer needed in the view. After checking all my objectAtIndex references preceding the modal presentation at length for two days, I decided to look at the UITableViewController subclass code itself. I found this:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
// Return the number of sections.
return 5;
}
Then the lightbulb went off. The index 4 being referred to related to my table view number of sections and the bound of [0 .. 1] referred to my current two table cell sections. Updating the return value to match the number of current table cell sections in the Storyboard table view resolved the issue.
Somewhere you are likely accessing _videos prior to initializing it. Most likely you'd doing it after init, but prior to loading the view. The fix for this kind of problem is to use accessors exclusively, and to lazy-initialize self.videos. This is one of many reasons never to access your ivars directly except in init and dealloc.
#interface ...
#property (nonatomic, readonly, strong) NSMutableArray *videos;
#end
#implementation ...
{
NSMutableArray *_videos; // Can't auto-synthesize. We override the only accessor.
}
- (NSMutableArray *)videos {
if (! _videos) {
_videos = [NSMutableArray new];
}
return _videos;
}
Now all references to self.videos will be initialized no matter when they happen.
You can also initialize videos correctly in init, which takes a little less code:
#interface ...
#property (nonatomic, readonly, strong) NSMutableArray *videos;
#end
#implementation ...
- (id)init {
self = [super init];
if (self) {
_videos = [NSMutableArray new];
}
return self;
}
I have passed dummy image name for images array like this,
arrImages = [NSArray arrayWithObjects:[UIImage imageNamed:#"some.png"]
The above line caused me error. So I changed #"some.png" with existed image like #"category.png".
This is worked for me. Make sure you are passing correct image name from your bundle.