ObjectAtIndex causes app to crash - iphone

When I do an NSLog of the contents of my NSMutableArray, it returns :
(
hat,
hat
)
So why is it that when I do an NSLog like so NSLog(#"%#", [pro.matches objectAtIndex:0]); it crashes with the error: *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
So strange
This is where I fill it:
[self.matches removeAllObjects];
NSArray *JSONarray = [[NSArray alloc] initWithArray:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]];
int i;
for (i=0; i<[JSONarray count]; i++) {
//[self.matches addObject:[JSONarray objectAtIndex:i]];
[self.matches addObject:#"hat"];
}
//NSLog(#"boys with bo%#", [[matches objectAtIndex:1] objectForKey:#"host"]);
block();
//JSON and add to matches.
}
}];
block();
and this is where i call it:
[pro refreshMatchesWithCallback:^
{
//[self.tableView reloadData];
NSLog(#"the count of a lifetime is %#", [pro.matches objectAtIndex:0]);
}];

When you first log the contents it has nothing in due to the way completion blocks work, try this:
[pro refreshMatchesWithCallback:^
{
//[self.tableView reloadData];
if(pro.matches.count > 0) {
NSLog(#"the count of a lifetime is %#", [pro.matches objectAtIndex:0]);
}
}];
Hope this Helps!
Sam

always prefer to use this approach
for(Object* obj in arra)
{
...
}
this will enter in loop if the counter is greater than 0. no check needed
Cheerz :P

Related

NSInternalInconsistencyException reason: '-[__NSCFArray replaceObjectAtIndex:withObject:]: mutating method sent to immutable object'

could you please help me to solve the following error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray replaceObjectAtIndex:withObject:]: mutating method sent to immutable object'
array_Info = [[NSMutableArray alloc] init];
array_Info = [dict_Temp objectForKey:#"Children"];
NSMutableArray *temp = [[NSMutableArray alloc] initWithArray:self.array_Info];
int ran, arrayIndexing = 0;
while ([temp count] != 0)
{
ran = arc4random();
if(ran < 0)
ran*=-1;
ran = ran % [temp count];
if([temp count] == 1)
ran = 0;
NSLog(#"%d %d",arrayIndexing,ran);
[self.array_Info replaceObjectAtIndex:arrayIndexing withObject:[temp objectAtIndex:ran]];
[temp removeObjectAtIndex:ran];
arrayIndexing++;
}
Presuming that array_Info is the backing variable for the self.array_Info property, you should change your second line to:
array_Info = [[dict_Temp objectForKey:#"Children"] mutableCopy];
This will give you the mutable array you need for the replaceObjectAtIndex:withObject: call.
It seems that self.array_Info is an immutable array. Make it mutable.

NSMutablearray define init issue

i have the following line of code
NSMutableArray *marray = [[NSArray arrayWithObjects: #"4", #"1", #"9", nil]mutableCopy];
and i want to replace it with the following line
NSMutableArray *marray = [[NSMutableArray alloc]initWithArray:garr];
where garr is global array from global method
the problem is that the code works fine when calling the first line but when using the second one the code crash , appreciate ur help and ideas thanks , iknow that the first one is NSArray but the garr variable source is NSMutable array
here is the code for garr
garr = [[NSMutableArray alloc]init];
for (int x = 0; x < 10; x++) {
[garr addObject:[NSNumber numberWithInt: arc4random()%200]];
here is the error msg
console error:2012-09-02 14:46:42.976 sort_alg[1561:207] -[NSCFNumber UTF8String]: unrecognized selector sent to instance 0x4b1a170 2012-09-02 14:46:42.978 sort_alg[1561:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFNumber UTF8String]: unrecognized selector sent to instance 0x4b1a170' * Call stack at first throw: –
this is the code that generates the end value
NSString *element;
NSEnumerator *iterator = [marray objectEnumerator];
while ((element = [iterator nextObject]) != nil)
printf("%s ", [element UTF8String]);
printf("\n");
[marray release]; // array needs to be released!
[pool release];
thanks
Problem lies in printf("%s ", [element UTF8String]);.
NSNumber has no UTF8String method, only a stringValue. You can't printf it either, but you can NSLog("%#", [element stringValue]), or NSLog("%d", [element intValue]) if you know it's an int.

How to delete in an NSMutableArray

I have an array which I store different classes which again hold different arrays. All arrays are defined as NSMutabelArrays.
When I want to delete an object in an array, my app crashes. This is my code:
NSLog(#"string to be deleted:%#", [[[self.myLibrary objectAtIndex:self.currentNoteBookNumber] tabReference] objectAtIndex:tid]);
NSLog(#"string to be deleted:%#", [[[self.myLibrary objectAtIndex:self.currentNoteBookNumber] tabColours] objectAtIndex:tid]);
NSLog(#"string to be deleted:%#", [[[self.myLibrary objectAtIndex:self.currentNoteBookNumber] tabTitles] objectAtIndex:tid]);
[[[self.myLibrary objectAtIndex:self.currentNoteBookNumber] tabReference] removeObjectAtIndex:tid];
[[[self.myLibrary objectAtIndex:self.currentNoteBookNumber] tabColours] removeObjectAtIndex:tid];
[[[self.myLibrary objectAtIndex:self.currentNoteBookNumber] tabTitles] removeObjectAtIndex:tid];
And this is the console output:
2011-05-01 22:03:40.788 M[61452:207] string to be deleted:2
2011-05-01 22:03:40.789 M[61452:207] string to be deleted:Orange
2011-05-01 22:03:40.791 M[61452:207] string to be deleted:Art
2011-05-01 22:03:40.806 M[61452:207] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'
I don't really know what I'm doing wrong. There is obviously something in the array, so it shouldn't be 0. I mean it is the ONLY thing stored in the array at the moment, but that shouldn't be a problem, I guess?
I'd be very grateful for any help on this.
EDIT:
I think I haven't provided enough code. This is the method in which I set up myLibrary:
-(void) setupLibrary {
myLibrary = [[NSMutableArray alloc] init];
NoteBook *newNoteBook = [[NoteBook alloc] init];
newNoteBook.titleName = #"TEST";
NSMutableArray *ttArray = [[NSMutableArray alloc] init];
[ttArray addObject:#"Art"];
NSMutableArray *tcArray = [[NSMutableArray alloc] init];
[tcArray addObject:#"Orange"];
NSMutableArray *trArray = [[NSMutableArray alloc] init];
[trArray addObject: [NSNumber numberWithInteger:2]];
newNoteBook.tabTitles = ttArray;
newNoteBook.tabColours = tcArray;
newNoteBook.tabReference = trArray;
[myLibrary addObject:newNoteBook];
currentNoteBookNumber = 0;
[newNoteBook release];
[ttArray release];
[tcArray release];
[trArray release];
}
Now it appears that if I delete, for instance, one object in the tabTitles array (e.g. "Art"), I delete the entire newNoteBook object. I.e. once I delete a string in tabTitles, all other strings at the same position in tabColours or tabReference will be deleted as well. Why is this so?
The following code will crash after I successfully deleted the string # position 0 in an array in my class which is stored in another array:
NSLog(#"string deleted:%#", [[[self.myLibrary objectAtIndex:0] tabReference] objectAtIndex:0]);
[[[self.myLibrary objectAtIndex:0] tabReference] removeObjectAtIndex:0];
NSLog(#"string deleted:%#", [[[self.myLibrary objectAtIndex:0] tabColours] objectAtIndex:0]);
[[[self.myLibrary objectAtIndex:0] tabColours] removeObjectAtIndex:0];
Don't know what's the problem here, but you should consider to keep your arrays safe:
if([yourArray count] > tid) {
[yourArray removeObjectAtIndex.tid;
}
Your error
-[NSMutableArray objectAtIndex:]: index 0
is telling that you are trying to get an object at index 0 not that you want to remove it. So I think what you did is you called the method where you have your reading and removing code 2 times in a row. Try to see it that is the case.

problem in searching table views

I am facing a problem in implementing the search functionality in Table Views... Here is the code i am implementing to search...
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
searchArray = [data boats];
for(Boat *boat in searchArray)
{
NSRange titleResultsRange = [[boat boatName] rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:boat];
}
[searchArray release];
searchArray = nil;
}
When the search bar starts getting edited, i call this...
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
//Remove all objects first.
[copyListOfItems removeAllObjects];
if([searchText length] > 0) {
[ovController.view removeFromSuperview];
searching = YES;
letUserSelectRow = YES;
self.tableView.scrollEnabled = YES;
[self searchTableView];
}
else {
[self.tableView insertSubview:ovController.view aboveSubview:self.parentViewController.view];
searching = NO;
letUserSelectRow = NO;
self.tableView.scrollEnabled = NO;
}
[self.tableView reloadData];
}
and i assign the value to table row using...
if(searching)
{
Boat *copyboat = [copyListOfItems objectAtIndex:[indexPath row]];
cell.textLabel.text = [copyboat boatName];
NSLog(#"%#", [copyboat boatName]);
}
else {
Boat *fullboat =[data.boats objectAtIndex:[indexPath row]];
cell.textLabel.text =[fullboat boatName];
}
But when i start typing the values in search bar, the app is crashing. I get different errors when i type different alphabets. I get errors like.
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]: index 6 beyond bounds [0 .. 5]'
or
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'
Sometime its also showing EXEC_BAD_ACCESS also... I am screwed right now. Can anyone please tell me what the error exactly is...???
When you create the subset of boat names, do you change the value of what you return in numberOfRowsInSection? It looks like the table is reloading and trying to find data for 7 rows, but you now only have data for six. Something like:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
if (searching) {
return [copyListOfItems count];
} else {
return [data count];
}
}

how to append from NSMutableArray

i try to append from NSMutableArray but the below exception, actually first 2 loop its giving result but the 3rd loop giving this exception
2009-12-04 12:01:19.044 AppBuzz[14562:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFString appendString:]: nil argument'
2009-12-04 12:01:19.057 AppBuzz[14562:207] Stack: (
820145437,
837578260,
819694387,
819694291,
814894619,
814804961,
17445,
23977,
18651,
19281,
862009284,
9035,
861597328,
861596264,
861928960,
861926972,
861925524,
858687888,
819893547,
819891231,
861592584,
861585968,
8749,
8612
)
terminate called after throwing an instance of 'NSException'
my code as below
for (int i = 0; i < [student count]; i++)
{
if([student objectAtIndex:i] != NULL)
{
dic = [student objectAtIndex:i];
tempName = [dic objectForKey:#"NAME"];
tempAvgMark = [[dic objectForKey:#"AVG_MARK"] intValue];
[data appendString:#"{\"name\":\""];
[data appendString:tempName]; // here i'm having prob
[data appendString:#"\",\"avg_mark\":\""];
//[data appendString:tempAvgMark];
[data appendString:#"\"}"];
}
}
NSLOG(#"Result - %#",data);
can anyone help for
1) to append [data appendString:tempName];
2) to append int value ([data appendString:tempAvgMark]; ) into data
thanks
You're trying to append a nil, which is illegal. You can easily get around this by changing the line in question to the following:
[data appendString:(tempName == nil ? #"" : tempName)];
Or replace that empty string with whatever else you want. To append a non-string value, convert it to a string like this:
[data appendString:[NSString stringWithFormat:#"%i", tempAvgMark]];
If tempAvgMark is not an 'int', you'll have to change the %i. For example, for NSNumbers, use %# instead.
The object for the key #"NAME" in the dictionary has to be a string, and to append an int you can use [string appendFormat:#"%d", someInt].
It appears from this message: NSCFString appendString:]: nil argument' that one of the dictionary values is null