Looping through an array, index error - ios

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];
}

Related

NSArray unrecognized selector sent to instance on Json

I am new to Objective-C And here I have a Json that I've stored into a NSArray. And I am trying to get the English, Dutch, Portuguese
{
English = (
One,
Two,
Three
);
Dutch = (
Een
);
Portuguese = (
Um,
Dois
}
And here's what I've done:
languageArray = result;
for (i = [languageArray count] - 1; i >= 0; i--)
{
NSString *languageTitle = [languageArray objectAtIndex:i];
NSLog(#"languageTitle %#", languageTitle);
}
And I have this error -[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x7f8c68e53610 but my languageArray count is 3. I don't know why I can't get the objectAtIndex:i I've tried to use objectAtIndex:0 but still the same result
just use
NSArray*languages = [result allKeys];
for getting values for languages you have to do this
NSMutableArray *mutableArray = [[NSMutableArray alloc]init];
for (int i=0 ; i<languages.count ; i++){
[mutableArray addObject:[result valueForKey:[languages objectAtIndex:indexpath.row]]];
}
So finally you have mutable array which contains values for every language as array;
You can get values for english with respect to index of language.
For example you can get values for Dutch as
NSArray *dutchValues = [mutableArray objectAtIndex:1];

Add an object in a specific position of a NSArray - iOS

Please suggestion only for NSArray.
NSArray *addressAry = [[arr1 valueForKey:#"var_offline_address"] componentsSeparatedByString:#"$#$"];
for (int i = 0; i<=addressAry.count; i++) {
NSString *str = [addressAry objectAtIndex:i];
if (str containsString:#"NA") {
NSString *strChange;
strChange = #"Address Not Available";
[myMutableArray insertObject:myObject atIndex:42];
To add an object to the front of the array, use 0 as the index:
[myMutableArray insertObject:myObject atIndex:0];
Use NSMutableArray. It has a method called:
- (void)insertObject:(ObjectType)anObject atIndex:(NSUInteger)index
Like:
[yourMutableArray insertObject: theObject atIndex: theIndex];
As it describes:
If index is already occupied, the objects at index and beyond are shifted by adding 1 to their indices to make room.
For more info see the official doc.

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.

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

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"]];
}

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