Error: index 1 beyond bounds [0 .. 0] - objective-c

I am a rookie in Xcode and I have been using the UITableViewController which shows this error.
This is the error message:
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
* First throw call stack:
(0x1c91012 0x10cee7e 0x1c330b4 0x36d0 0xc58d5 0xc5b3d 0xacce83 0x1c50376 0x1c4fe06 0x1c37a82 0x1c36f44 0x1c36e1b 0x1beb7e3 0x1beb668 0x1665c 0x2132 0x2065)
libc++abi.dylib: terminate called throwing an exception
(lldb)
This is my code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.row == 0) {
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/GetDetail.php?choice=row0"];
NSArray *arrayImagesNames = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strURL]];
arrayDataFromServer2 = [[NSMutableArray alloc]init];
NSEnumerator *enumForNames = [arrayImagesNames objectEnumerator];
id objName;
while ( objName = [enumForNames nextObject]) {
[arrayDataFromServer2 addObject:[NSDictionary dictionaryWithObjectsAndKeys:objName, #"name", nil]];
}
NSString *nn = [[arrayDataFromServer2 objectAtIndex:indexPath.row] objectForKey:#"name"];
row1 = [nn intValue];
NSLog(#"%d", row1);
CompanyProfileViewController *profile = [self.storyboard instantiateViewControllerWithIdentifier:#"Profile"];
[self.navigationController pushViewController:profile animated:YES];
profile.profileid = row1;
NSLog(#"%d", profile.profileid);
}
if (indexPath.row == 1) {
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/GetDetail.php?choice=row1"];
NSArray *arrayImagesNames = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strURL]];
arrayDataFromServer2 = [[NSMutableArray alloc]init];
NSEnumerator *enumForNames = [arrayImagesNames objectEnumerator];
id objName;
while (objName = [enumForNames nextObject]) {
[arrayDataFromServer2 addObject:[NSDictionary dictionaryWithObjectsAndKeys:objName, #"name", nil]];
}
NSString *nn = [[arrayDataFromServer2 objectAtIndex:indexPath.row] objectForKey:#"name"];
row1 = [nn intValue];
NSLog(#"%d", row1);
CompanyProfileViewController *profile = [self.storyboard instantiateViewControllerWithIdentifier:#"Profile"];
[self.navigationController pushViewController:profile animated:YES];
profile.profileid = row1;
NSLog(#"%d", profile.profileid);
}
if (indexPath.row == 2) {
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/GetDetail.php?choice=row2"];
NSArray *arrayImagesNames = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strURL]];
arrayDataFromServer2 = [[NSMutableArray alloc]init];
NSEnumerator *enumForNames = [arrayImagesNames objectEnumerator];
id objName;
while ( objName = [enumForNames nextObject]) {
[arrayDataFromServer2 addObject:[NSDictionary dictionaryWithObjectsAndKeys:objName, #"name", nil]];
}
NSString *nn = [[arrayDataFromServer2 objectAtIndex:indexPath.row] objectForKey:#"name"];
row1 = [nn intValue];
NSLog(#"%d", row1);
CompanyProfileViewController *profile = [self.storyboard instantiateViewControllerWithIdentifier:#"Profile"];
[self.navigationController pushViewController:profile animated:YES];
profile.profileid = row1;
NSLog(#"%d", profile.profileid);
}
if (indexPath.row == 3) {
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/GetDetail.php?choice=row3"];
NSArray *arrayImagesNames = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strURL]];
arrayDataFromServer2 = [[NSMutableArray alloc]init];
NSEnumerator *enumForNames = [arrayImagesNames objectEnumerator];
id objName;
while ( objName = [enumForNames nextObject]) {
[arrayDataFromServer2 addObject:[NSDictionary dictionaryWithObjectsAndKeys:objName, #"name", nil]];
}
NSString *nn = [[arrayDataFromServer2 objectAtIndex:indexPath.row] objectForKey:#"name"];
row1 = [nn intValue];
NSLog(#"%d", row1);
CompanyProfileViewController *profile = [self.storyboard instantiateViewControllerWithIdentifier:#"Profile"];
[self.navigationController pushViewController:profile animated:YES];
profile.profileid = row1;
NSLog(#"%d", profile.profileid);
}
}
When I click on the second cell (index.row == 1) this error would occur.
I have used breakpoint and the error was on the line:
"NSString *nn = [[arrayDataFromServer2 objectAtIndex:indexPath.row] objectForKey:#"name"];"
Please Help!

Swift 4
after more time i am get the love for this Error 😄
when you use the tableView from the storyboard and implementing in your code :
hint that and compare :
between the number of section and numberOfRowsInSection == storyboard and code
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}

You have an array and you have either 0 or 1 elements in it. Now you are trying to extract 2nd element from it, [0] is first, and [1] is second.
EDIT:
As you are not sure when the array will contain 1 or more objects. Therefore you can use as:
NSString *nn=nil;
if([arrayDataFromServer2 count]>1){
nn = [[arrayDataFromServer2 objectAtIndex:indexPath.row] objectForKey:#"name"];
}

Related

How to form an array of dictionaries for multilevel(any number) tableview from the core data object

I need to create array of dictionaries, of data coming from a database object. This array of dictionaries can be of multiple level,and has a parent child relationship depending upon the level.
From the array form I need to create a multilevel table view (level can be any depending upon the data loaded)
Depending upon the catal_id of the coredata object, next set of Catal objects are loaded from the database. Code supporting is shown as below.
I want to create the array as shown in the image
From the above load of loadMainCatalData I am able to load the table but on didSelectRowAtIndexPath I am not able to form the proper array for the expand collapse table. Catal object gets added twice, on viewDidLoad.
There is some issue with function.
**Please help to form the proper array to load the table. Stuck here **.
The coredata object is of the below format:
<__NSArrayM 0x109c3b7a0>(
<Catal: 0x104cccfb0>
(entity: Catal; id: 0xd000000008880006 <x-coredata://F849E220-C905-4359-8CD5-18D5E35FC13A/Catal/p546> ; data: {
breadcrumb = "";
"catal_id" = "SNV2";
"id_ni" = 1;
"id_parent" = 0;
imgId = 1;
title = "Adventure";
"nb_element" = 1010;
order = 38;
}),
<Catal: 0x104ccd3f0> (entity: Catal; id: 0xd000000006e40006 <x-coredata://F849E220-C905-4359-8CD5-18D5E35FC13A/Catal/p441> ; data: {
breadcrumb = "";
"catal_id" = "SNV1";
"id_ni" = 1;
"id_parent" = 0;
imgId = 38;
title = Gros;
"nb_element" = 1366;
order = 82;
}),
<Catal: 0x104ccd6e0> (entity: Catal; id: 0xd00000000a500006 <x-coredata://F849E220-C905-4359-8CD5-18D5E35FC13A/Catal/p660> ; data: <fault>),
<Catal: 0x104ccd790> (entity: Catal; id: 0xd000000005d40006 <x-coredata://F849E220-C905-4359-8CD5-18D5E35FC13A/Catal/p373> ; data: <fault>),
<Catal: 0x104ccd940> (entity: Catal; id: 0xd00000000acc0006 <x-coredata://F849E220-C905-4359-8CD5-18D5E35FC13A/Catal/p691> ; data: <fault>)
)
My code goes as below
- (void)viewDidLoad {
[super viewDidLoad];
if (!self.catalList || self.catalList.count == 0) {
[self loadDataCatal];
isAlreadyInserted = NO;
}
}
- (void)loadDataCatal{
[self loadMainCatalData];
self.arForTable = [NSMutableArray array];
[self.arForTable addObjectsFromArray:self.arrayOriginal];
}
-(void)loadMainCatalData {
NSMutableArray *arrCatalList = [[NSMutableArray alloc] init];
if (catLevel == NULL){
[arrCatalList addObjectsFromArray:[Catal fillDataCatal:#"0" :#"0"]];
}
self.arrayOriginal = [NSMutableArray array];
for (Catal *objCatal in arrCatalList){
ProductCategoryFilter *objProductCatFilter = [[ProductCategoryFilter alloc] init];
[objProductCatFilter setCatalCategory:objCatal];
NSMutableArray *arr = [self loadSubCatalData:objCatal];
[objProductCatFilter setArrCatalSubCategory:arr];
[self.arrayOriginal addObject:objProductCatFilter];
}
}
-(NSMutableArray *)loadSubCatalData:(Catal *)objCatal{
NSMutableArray *arrSubCatal = [NSMutableArray array];
ProductCategoryFilter *objProductCatFilter = [[ProductCategoryFilter alloc] init];
[objProductCatFilter setCatalCategory:objCatal];
NSArray *arrCatal = [Catal fillDataCatal:objCatal.catal_id :#""];
NSMutableArray *arrSubCat = [NSMutableArray array];
for (Catal *subCatal in arrCatal){
ProductCategoryFilter *objSubCatFilter = [[ProductCategoryFilter alloc] init];
[objSubCatFilter setCatalCategory:subCatal];
NSMutableArray *arr = [self loadSubCatalData:subCatal];
[objSubCatFilter setArrCatalSubCategory:arr];
[arrSubCat addObject:objSubCatFilter];
}
[objProductCatFilter setArrCatalSubCategory:arrSubCat];
[arrSubCatal addObject:objProductCatFilter];
return arrSubCatal;
}
// the ProductCategoryFilter class
#import <Foundation/Foundation.h>
#import "Catal+CoreDataClass.h"
#interface ProductCategoryFilter : NSObject
#property (nonatomic,strong) Catal* catalCategory;
#property (nonatomic,strong) NSMutableArray * arrCatalSubCategory;
#end
// Catal CoreDataObject
#import <Foundation/Foundation.h>
#import "Catal+CoreDataClass.h"
+(BOOL)fillSubDataCatal:(NSString *)catal_id
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context = [[CoreDataHelper getInstance] managedObjectContext];
NSError *error;
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Catal" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSPredicate *predicate;
predicate = [NSPredicate predicateWithFormat:#"id_parent == %#", catal_id];
[fetchRequest setPredicate:predicate];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
DebugLog(#"[fetchedObjects count] : %lu",(unsigned long)fetchedObjects.count);
if([fetchedObjects count] > 0)
{
return true;
}
return false;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier =#"AMG_PP_SubCategoryTableCell";
AMG_PP_SubCategoryTableCell *cell = (AMG_PP_SubCategoryTableCell *) [self.tblProductCategory dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil){
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
cell =(AMG_PP_SubCategoryTableCell *)[nib objectAtIndex:0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
ProductCategoryFilter *objCat = [self.arForTable objectAtIndex:indexPath.row];
[cell.imgRadio setImage:[UIImage imageNamed:#"PlusIcon"]];
cell.textLabel.text = objCat.catalCategory.libelle; //] [ valueForKey:#"name"];
// [cell setIndentationLevel:[[[self.arForTable objectAtIndex:indexPath.row] valueForKey:#"level"] intValue]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
AMG_PP_SubCategoryTableCell *cell = (AMG_PP_SubCategoryTableCell *)[self.tblProductCategory cellForRowAtIndexPath:indexPath];
[self.tblProductCategory deselectRowAtIndexPath:indexPath animated:YES];
ProductCategoryFilter *objCatal = [self.arForTable objectAtIndex:indexPath.row];
if([[objCatal arrCatalSubCategory] count] > 0) {
NSMutableArray *ar=[objCatal arrCatalSubCategory];
if(ar != nil){
isAlreadyInserted=NO;
for(ProductCategoryFilter *dInner in ar ){
NSInteger index=[self.arForTable indexOfObjectIdenticalTo:dInner];
isAlreadyInserted=(index>0 && index!=NSIntegerMax);
if(isAlreadyInserted) break;
}
if(isAlreadyInserted) {
[self miniMizeThisRows:ar];
} else {
NSUInteger count=indexPath.row+1;
NSMutableArray *arCells=[NSMutableArray array];
for(ProductCategoryFilter *dInner in ar ){
[arCells addObject:[NSIndexPath indexPathForRow:count inSection:0]];
[self.arForTable insertObject:dInner atIndex:count++];
}
[cell.imgRadio setImage:[UIImage imageNamed:#"MinusIcon"]];
[tableView insertRowsAtIndexPaths:arCells withRowAnimation:UITableViewRowAnimationLeft];
}
}
}
}
-(void)miniMizeThisRows:(NSArray*)ar{
for(ProductCategoryFilter *dInner in ar ){
NSUInteger indexToRemove=[self.arForTable indexOfObjectIdenticalTo:dInner];
NSMutableArray *arInner=[dInner arrCatalSubCategory];
if(arInner && [arInner count]>0){
if (arInner != nil) {
[self miniMizeThisRows:arInner];
}
}
if([self.arForTable indexOfObjectIdenticalTo:dInner]!=NSNotFound) {
[self.arForTable removeObjectIdenticalTo:dInner];
[self.tblProductCategory deleteRowsAtIndexPaths:[NSArray arrayWithObject:
[NSIndexPath indexPathForRow:indexToRemove inSection:0]
]
withRowAnimation:UITableViewRowAnimationRight];
}
}
}
Here's the simple code which help you in understanding the how to create a array of dictionary :
var arrayOfDict = [[String : String]]()
let dict1 = ["FirstName" : "Abc" , "LastName" : "XYZ"]
let dict2 = ["HouseNo" : "WW49", "Locality" : "GymKhana"]
let dict3 = ["City" : "mnb", "State" : "lkop" , "Country" : "mkl"]
arrayOfDict.append(dict1)
arrayOfDict.append(dict2)
arrayOfDict.append(dict3)
print(arrayOfDict)

How to remove array object from for loop

please Help me. I stuck here when deleting an object from array.
for (id obj in self.arrSavedImage)
{
Class cls = [obj class];
id newObj = [[cls alloc] init];
//UIImage *img = nil;
if([newObj isKindOfClass:[UIImage class]]){
NSLog(#"class type %#", [newObj class]);
}
else{
[self.arrSavedImage removeObject:obj];
}
}
Thank You.
You shouldn't remove objects from an array you are enumerating over. Better is to keep a list of the objects you want to delete, and then delete them when you've finished enumerating the original array:
NSMutableArray *toDelete = [NSMutableArray new];
for (id obj in self.arrSavedImage)
{
Class cls = [obj class];
id newObj = [[cls alloc] init];
if([newObj isKindOfClass:[UIImage class]]){
NSLog(#"class type %#", [newObj class]);
}
else{
[toDelete addObject:obj];
}
}
for (id obj in toDelete)
[self.arrSavedImage removeObject:obj];
NSMutableArray *itemsToDelete = [[NSMutableArray alloc] init];
for (id obj in self.arrSavedImage)
{
Class cls = [obj class];
id newObj = [[cls alloc] init];
//UIImage *img = nil;
if([newObj isKindOfClass:[UIImage class]]){
NSLog(#"class type %#", [newObj class]);
}
else{
[itemsToDelete addObject:obj];
}
}
[self.arrSavedImage removeObjectsInArray:itemsToDelete];
You can not remove the object in array while in loop.
You should create a new array with existing array and remove objects from it. Then replace the old array with editedArray.
NSMutableArray * editedArray = [[NSMutableArray alloc] initWithArray:self.arrSavedImage];
for (id obj in self.arrSavedImage)
{
Class cls = [obj class];
id newObj = [[cls alloc] init];
//UIImage *img = nil;
if([newObj isKindOfClass:[UIImage class]]){
NSLog(#"class type %#", [newObj class]);
}
else{
[editedArray removeObject:obj];
}
}
[self.arrSavedImage setArray:editedArray];
editedArray = nil;

NSMutableArray- removeObject results with removing object and a nil element

Firstly, I am new with Objective C.
I have my class Song that has a pair of attributes.
In my main class i got a variable allSongs that is a NSMutableArray and in this array have I added all my song-objects.
My problem comes when trying to call [self.allSongs removeObject:OBJECT];
Using the debugger, I can see that before the call, the list looks as expected. But after the call it will result that the targeted object will be removed but also the first element in the array will turn to nil.
Is this a common pointer problem or what?
Here is my code:
in h file
#property (nonatomic, strong) NSMutableArray *songs;
#property (nonatomic, strong) NSMutableArray *allChapters;
in m file
- (void)viewDidLoad
{
self.chosenChapter = [[NSString alloc]initWithFormat:self.chosenChapter];
self.allChapters = [[NSMutableArray alloc]init];
//Chapter names and chapter page range
chapters = [[NSArray alloc]initWithObjects:#"chapter1", #"chapter2", #"chapter3", nil];
chaptersRange = [[NSArray alloc]initWithObjects:#"25", #"51", #"88", nil];
//Filnames of every song
files = [[NSMutableArray alloc] initWithObjects:#"test", #"Feta_fransyskor", nil];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey: #"page" ascending: YES];
self.songs = [[NSMutableArray alloc]init];
for(int i = 0; i < chapters.count; i++){
Song *chapter = [[Song alloc]init];
[chapter setPage:(NSString *)self.chaptersRange[i]];
[chapter setTitle:(NSString *)self.chapters[i]];
[self.allChapters addObject:chapter];
[self.songs addObject:chapter];
}
NSString *filePath;
int i;
for (i = 0; i < files.count; i++) {
filePath = [[NSBundle mainBundle] pathForResource:files[i] ofType:#"txt"];
if(filePath){
NSError *error;
NSString *textFromfile = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error: &error];
/*
index
0 for page number
1 for title name
2 for melody name
3 -> for lyrics
*/
NSMutableArray *newLineseparatedText = (NSMutableArray *)[textFromfile componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
if(newLineseparatedText){
Song *newSong = [[Song alloc]init];
[newSong setPage:newLineseparatedText[0]];
[newSong setTitle:newLineseparatedText[1]];
[newSong setMelody:newLineseparatedText[2]];
[newLineseparatedText removeObjectAtIndex:0]; //remove page number
[newLineseparatedText removeObjectAtIndex:0]; //remove title name
[newLineseparatedText removeObjectAtIndex:0]; //remove melody name
[newSong setLyric:[newLineseparatedText componentsJoinedByString:#"\n"]];
[songs addObject:newSong];
}
}
}
[self.songs sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[super viewDidLoad];
}
-(void)addChapters{
for(int i = 0; i < self.allChapters.count; i++){
if([self.songs containsObject:self.allChapters[i]] == false)
[self.songs addObject:self.allChapters[i]];
}
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey: #"page" ascending: YES];
[self.songs sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
}
-(void)addChapters{
for(int i = 0; i < self.allChapters.count; i++){
if([self.songs containsObject:self.allChapters[i]] == false)
[self.songs addObject:self.allChapters[i]];
}
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey: #"page" ascending: YES];
[self.songs sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
}
-(void)removeChaptersExcept:(Song *) chapter{
for(int i = 0; i < self.allChapters.count; i++){
if(self.allChapters[i] != chapter && [self.songs containsObject:self.allChapters[i]])
[self.songs removeObject:self.allChapters[i]];
}
}
last line of this code is were i get an error, as the mutableArray has a couple of nil elements.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if([self.chosenChapter isEqualToString:#"Alla"]){
[self addChapters];
}
else{
Song *chapter = nil;
for(int i = 0; i < self.allChapters.count; i++){
if([((Song *)self.allChapters[i]).title isEqualToString:self.chosenChapter]){
chapter = self.allChapters[i];
break;
}
}
[self addChapters];
[self removeChaptersExcept:chapter];
}
NSString *cellIdentifier = nil;
UITableViewCell *cell = nil;
NSString *page = ((Song *)self.songs[indexPath.row]).page;
and here are some screen bumps
This is before removing first object
This is after the first object was removed. You see how one element disapeared as expected and the other is set too nil?
Sometimes the Variables View shows incorrect values.
An array can't contain nil values, so this is definitely a case where the values are wrong.
You state that your application crashes on this line:
NSString *page = ((Song *)self.songs[indexPath.row]).page;
My guess is that self.songs[indexPath.row] simply doesn't have a property called page.
Try to replace this line with this code:
Song *s = self.songs[indexPath.row];
if (s == nil)
{
NSLog("Song is nil! How can that be?");
}
else
{
NSLog("Page is %#", s.page);
}
It will help you pin-point the problem. Good luck.

-[__NSCFConstantString allKeys]: unrecognized selector sent to instance 0xf9ac8

My app when I run it on my phone I get this error:
I just tried to parse a json and trying to use images in two column of custom cell, but my images on scroll are mis-placed.
int index=indexPath.row*2;
int newindex=index+1;
NSDictionary *u = [[results objectAtIndex:index]mutableCopy ];
NSLog(#"NSDictionary *u = [results objectAtIndex:index] %#",u);
NSDictionary *u1 = [[results objectAtIndex:newindex]mutableCopy];
NSLog(#"NSDictionary *u1 = [results objectAtIndex:newindex] %#",u1);
But if i use both index and newindex same value it works.
:-
:-
Code :
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil suffix:(NSString *)_suffix{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.suffix = _suffix;
}
return self;
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)_tableView{
return 1;
}
//my new
- (NSInteger)tableView:(UITableView *)_tableView numberOfRowsInSection:(NSInteger)section{
int resultCount = [results count];
labelResultsCount.text = [NSString stringWithFormat:#"%d",resultCount];
return resultCount/2;
}
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// NSString* CellIdentifier = [NSString stringWithFormat:#"ident_%d",indexPath.row];
static NSString *CellIdentifier = #"ResultCell";
ResultCell *cell = (ResultCell *)[_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil){
NSArray *a = [[NSBundle mainBundle] loadNibNamed:#"ResultCell" owner:self options:nil];
cell = (ResultCell *)[a objectAtIndex:0];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
int index=[(indexPath.row*2) copy];
int newindex=[(index+1) copy];
// save badge in dictionaory and get here and show in lable
NSDictionary *u = [[results objectAtIndex:index]mutableCopy ];
NSLog(#"NSDictionary *u = [results objectAtIndex:newindex] %#",u);
NSDictionary *u1 = [[results objectAtIndex:newindex]mutableCopy];
NSLog(#"NSDictionary *u1 = [results objectAtIndex:indexPath.row*2+1 newindex] %#",u1);
#try {
/* fullName */
NSString *nickName = [u objectForKey:#"nickName"];
cell.labelName.text = nickName;
NSString *nickName1 = [u1 objectForKey:#"nickName"];
cell.labelName1.text = nickName1;
/* chat notification*/
cell.imageViewNotification.hidden=0;
cell.imageViewNotification1.hidden=0;
NSString *badge = [u objectForKey:#"badge"];
NSString *badge1 = [u1 objectForKey:#"badge"];
if([badge intValue]>0)
{
cell.imageViewNotification.hidden=0;
cell.labelNotification.text = badge;
NSLog(#"inside > 0 %#",badge);
}
else if([badge intValue]<=0)
{
cell.imageViewNotification.hidden=1;
cell.labelNotification.text=#"";
NSLog(#"%#",badge);
}
if([badge1 intValue]>0)
{
cell.imageViewNotification1.hidden=0;
cell.labelNotification1.text = badge1;
NSLog(#"inside > 0 %#",badge1);
}
else if([badge1 intValue]<=0)
{
cell.imageViewNotification1.hidden=1;
cell.labelNotification1.text=#"";
NSLog(#"%#",badge1);
}
/*..................*/
/* distance */
id distance = [u objectForKey:#"distance"];
if([distance isKindOfClass:[NSString class]]){
cell.labelDistance.text = distance;
cell.imageViewDistance.hidden = 0;
}else{
cell.imageViewDistance.hidden = 1;
cell.labelDistance.text = #"";
}
id distance1 = [u1 objectForKey:#"distance"];
if([distance1 isKindOfClass:[NSString class]]){
cell.labelDistance1.text = distance1;
cell.imageViewDistance1.hidden = 0;
}else{
cell.imageViewDistance1.hidden = 1;
cell.labelDistance1.text = #"";
}
/* online */
NSNumber *online = [u objectForKey:#"online"];
cell.imageViewOnline.image = [online intValue] ? [UIImage imageNamed:#"circle_online.png"] : [UIImage imageNamed:#"circle_offline_red.png"];
NSNumber *online1 = [u1 objectForKey:#"online"];
cell.imageViewOnline1.image = [online1 intValue] ? [UIImage imageNamed:#"circle_online.png"] : [UIImage imageNamed:#"circle_offline_red.png"];
/* buttonProfile */
id d = [u objectForKey:#"thumbnails"];
id d1 = [u1 objectForKey:#"thumbnails"];
if([d isKindOfClass:[NSDictionary class]] ||[d1 isKindOfClass:[NSDictionary class]]){
if([[d allKeys] count]>0 ||[[d1 allKeys] count]>0){
NSString *imageSuffix = [d objectForKey:#"icon"];
NSString *imageSuffix1 = [d1 objectForKey:#"icon"];
NSLog(#"[d allKeys] count]%#", d);
NSLog(#"[d1 allKeys] count]%#", d1);
UIImage *image = [[SharingCenter sharedManager] imageFromCache:imageSuffix];
UIImage *image1 = [[SharingCenter sharedManager] imageFromCache:imageSuffix1];
if(image||image1)
{
[cell.buttonUserProfile setBackgroundImage:image forState:UIControlStateNormal];
[cell.buttonUserProfile1 setBackgroundImage:image1 forState:UIControlStateNormal];
}
else{
NSString *gender = [u objectForKey:#"gender"];
NSString *gender1 = [u1 objectForKey:#"gender"];
UIImage *profileDefualtImage = [gender isEqualToString:#"M"] ? [UIImage imageNamed:#"no_photo_male.png"] : [UIImage imageNamed:#"no_photo_female.png"];
UIImage *profileDefualtImage1 = [gender1 isEqualToString:#"M"] ? [UIImage imageNamed:#"no_photo_male.png"] : [UIImage imageNamed:#"no_photo_female.png"];
[cell.buttonUserProfile setBackgroundImage:profileDefualtImage forState:UIControlStateNormal];
[cell.buttonUserProfile1 setBackgroundImage:profileDefualtImage1 forState:UIControlStateNormal];
/* downlowd Image */
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",WebServicePrefix,imageSuffix]];
__block
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
request.delegate = self;
[request setPostValue:[NSString stringWithFormat:#"%f",[[SharingCenter sharedManager] currentCoordinate].latitude] forKey:#"lat"];
[request setPostValue:[NSString stringWithFormat:#"%f",[[SharingCenter sharedManager] currentCoordinate].longitude] forKey:#"lon"];
// [[[SharingCenter sharedManager] imagesCache] removeAllObjects];
[request setCompletionBlock:^{
NSData *imageData = [request responseData];
if(imageData){
UIImage *image = [UIImage imageWithData:imageData];
if(image){
[[[SharingCenter sharedManager] imagesCache] setObject:image forKey:imageSuffix];
if([[self.tableView indexPathsForVisibleRows] containsObject:indexPath]){
ResultCell *cell = (ResultCell *)[self.tableView cellForRowAtIndexPath:indexPath];
[cell.buttonUserProfile setBackgroundImage:image forState:UIControlStateNormal];
}
}
}
}];
[request setFailedBlock:^{
NSError *error = request.error;
NSLog(#"%#",error);
}];
/* downlowd Image */
NSURL *url1 = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",WebServicePrefix,imageSuffix1]];
__block
ASIFormDataRequest *request1 = [ASIFormDataRequest requestWithURL:url1];
request1.delegate = self;
[request1 setPostValue:[NSString stringWithFormat:#"%f",[[SharingCenter sharedManager] currentCoordinate].latitude] forKey:#"lat"];
[request1 setPostValue:[NSString stringWithFormat:#"%f",[[SharingCenter sharedManager] currentCoordinate].longitude] forKey:#"lon"];
// [[[SharingCenter sharedManager] imagesCache] removeAllObjects];
[request1 setCompletionBlock:^{
NSData *imageData1 = [request1 responseData];
if(imageData1){
UIImage *image1 = [UIImage imageWithData:imageData1];
if(image1){
[[[SharingCenter sharedManager] imagesCache] setObject:image1 forKey:imageSuffix1];
if([[self.tableView indexPathsForVisibleRows] containsObject:indexPath]){
ResultCell *cell = (ResultCell *)[self.tableView cellForRowAtIndexPath:indexPath];
[cell.buttonUserProfile1 setBackgroundImage:image1 forState:UIControlStateNormal];
}
}
}
}];
[request1 setFailedBlock:^{
NSError *error = request1.error;
NSLog(#"%#",error);
}];
[[self networkQueue] addOperation:request];
[[self networkQueue] addOperation:request1];
}
}
}
else{
NSString *gender = [u objectForKey:#"gender"];
NSString *gender1 = [u1 objectForKey:#"gender"];
UIImage *profileDefualtImage = [gender isEqualToString:#"M"] ? [UIImage imageNamed:#"no_photo_male.png"] : [UIImage imageNamed:#"no_photo_female.png"];
[cell.buttonUserProfile setBackgroundImage:profileDefualtImage forState:UIControlStateNormal];
UIImage *profileDefualtImage1 = [gender1 isEqualToString:#"M"] ? [UIImage imageNamed:#"no_photo_male.png"] : [UIImage imageNamed:#"no_photo_female.png"];
[cell.buttonUserProfile1 setBackgroundImage:profileDefualtImage1 forState:UIControlStateNormal];
}
/* pickStatus */
NSNumber *pickStatus = [u objectForKey:#"pick_status"];
NSNumber *pickStatus1 = [u1 objectForKey:#"pick_status"];
switch ([pickStatus intValue]) {
case 0:
cell.imageViewBorder.image = [UIImage imageNamed:#"border_yellow_transperent.png"];
cell.buttonUserPick.enabled = 1;
[cell.buttonUserPick setBackgroundImage:[UIImage imageNamed:#"button_circle_pick.png"] forState:UIControlStateNormal];
break;
case 1:
cell.imageViewBorder.image = [UIImage imageNamed:#"border_red_transperent.png"];
cell.buttonUserPick.enabled = 0;
[cell.buttonUserPick setBackgroundImage:[UIImage imageNamed:#"button_circle_wait.png"] forState:UIControlStateDisabled];
break;
case 2:
cell.imageViewBorder.image = [UIImage imageNamed:#"border_red_transperent.png"];
cell.buttonUserPick.enabled = 1;
[cell.buttonUserPick setBackgroundImage:[UIImage imageNamed:#"button_circle_pick.png"] forState:UIControlStateNormal];
break;
case 3:
cell.imageViewBorder.image = [UIImage imageNamed:#"border_red_transperent.png"];
cell.buttonUserPick.enabled = 0;
[cell.buttonUserPick setBackgroundImage:[UIImage imageNamed:#"button_circle_date.png"] forState:UIControlStateDisabled];
break;
default:
break;
}
switch ([pickStatus1 intValue]) {
case 0:
cell.imageViewBorder1.image = [UIImage imageNamed:#"border_yellow_transperent.png"];
cell.buttonUserPick1.enabled = 1;
[cell.buttonUserPick1 setBackgroundImage:[UIImage imageNamed:#"button_circle_pick.png"] forState:UIControlStateNormal];
break;
case 1:
cell.imageViewBorder1.image = [UIImage imageNamed:#"border_red_transperent.png"];
cell.buttonUserPick1.enabled = 0;
[cell.buttonUserPick1 setBackgroundImage:[UIImage imageNamed:#"button_circle_wait.png"] forState:UIControlStateDisabled];
break;
case 2:
cell.imageViewBorder1.image = [UIImage imageNamed:#"border_red_transperent.png"];
cell.buttonUserPick1.enabled = 1;
[cell.buttonUserPick1 setBackgroundImage:[UIImage imageNamed:#"button_circle_pick.png"] forState:UIControlStateNormal];
break;
case 3:
cell.imageViewBorder1.image = [UIImage imageNamed:#"border_red_transperent.png"];
cell.buttonUserPick1.enabled = 0;
[cell.buttonUserPick1 setBackgroundImage:[UIImage imageNamed:#"button_circle_date.png"] forState:UIControlStateDisabled];
break;
default:
break;
}
}
#catch (NSException * e) {
NSLog(#"%#",e);
}
#finally {
return cell;
}
}
Educated guess:
This line causes your problem:
if([d isKindOfClass:[NSDictionary class]] ||[d1 isKindOfClass:[NSDictionary class]]){
if([[d allKeys] count]>0 ||[[d1 allKeys] count]>0){
There are 4 different possibilities how the first if will come out:
d and d1 are both NSStrings. Line 2 will not be called
d is NSDictionary, d1 is a NSString. Line 2 will be called
d is NSString, d1 is a NSDictionary. Line 2 will be called
d and d1 are both NSDictionaries. Line 2 will be called.
First case is no problem at all. Last case neither. In case 2 and 3 allKeys will be called on a object that is not a NSDictionary.
You should probably replace it with an "if" that needs both tests to be true.
if([d isKindOfClass:[NSDictionary class]] && [d1 isKindOfClass:[NSDictionary class]]){
^^
Another option would be to check individually.
if([d isKindOfClass:[NSDictionary class]]) {
x = [d allKeys];
}
if([d1 isKindOfClass:[NSDictionary class]]) {
x = [d1 allKeys];
}
You are probably doing something to those NSDictionary objects somewhere, reading their allKeys. But my guess is that the objects you try to fetch from that results array aren't NSDictionary objects but NSString objects.
Try logging their class property to see what you are dealing with (you can also find this out by just looking at the JSON of course).
NSDictionary *u = [[results objectAtIndex:index]mutableCopy ];
NSLog(#"u Class: %#", [u class]);
Also, why are you making a mutableCopy of the object right to a non-mutable NSDictionary object.
Using the following should do the trick normally:
NSDictionary* u = [results objectAtIndex:index];
NSLog(#"u Class: %#", [u class]);
That's a lot of code to look through, but I think this could be the problem:
if([d isKindOfClass:[NSDictionary class]] ||[d1 isKindOfClass:[NSDictionary class]]){
if([[d allKeys] count]>0 ||[[d1 allKeys] count]>0){
This if statement will pass if either d or d1 is a dictionary. If one isn't, it would cause that error you see on the second line. Log the class of d and d1 to see if they're both dictionaries.

Application crashes when searching ONE word

I'm making my UISearchBar working and i've noticed that if i type a word, just ONE, contained in more controllers (for example "a") and i select a row, i get an unexpected crash. If i search for more than a word it works, even if contained in more than 1 controller.
i'm getting a NSRangeException:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSArray objectAtIndex:]: index 9 beyond bounds [0 .. 8]'
at line
cellValue = [array objectAtIndex:indexPath.row];
of my code (i have 3 sections)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//Get the nib
NSString *cellValue = nil;
if(searching)
cellValue = [copyListOfItems objectAtIndex:indexPath.row];
else {
NSDictionary *dictionary =[listaOggetti objectAtIndex:indexPath.row];
NSArray *array = [dictionary objectForKey:#"Elementi"];
cellValue = [array objectAtIndex:indexPath.row];
}
NSDictionary *dict = [listaOggetti objectAtIndex:indexPath.section];
NSArray *array = [dict objectForKey:#"Elementi"];
cellValue = [array objectAtIndex:indexPath.row] ; //here's the error
if (indexPath.section == 0)
{
if ([cellValue isEqual: #"FirstNib"]){
FIrstViewController *firstController = [[FirstViewController alloc] initWithNibName:#"FirstViewController" bundle:nil];
[self.navigationController pushViewController:appsController animated:YES];
[firstController release];
if ([cellValue isEqual: #"SecondNib"]){
secondViewController *secondController = [[SecondViewController alloc] initWithNibName:#"secondViewController" bundle:nil];
[self.navigationController pushViewController:secondController animated:YES];
[secondController release];
}
//and so on
}
if (indexPath.section == 1){
if ([cellValue isEqual: #"ThirdNib"]){
ThirdViewController *firstController = [[ThirdViewController alloc] initWithNibName:#"ThirdViewController" bundle:nil];
[self.navigationController pushViewController:ThirdController animated:YES];
[ThirdController release];
}
//and so on
}
if (indexPath.section == 2) {
if ([cellValue isEqual #"FourthNib"]){
FourthViewController *firstController = [[FourthViewController alloc] initWithNibName:#"FourthViewController" bundle:nil];
[self.navigationController pushViewController:FourthController animated:YES];
[FourthController release];
}
}
(the line is not the one in the IF state)
Now. I know that it goes over the array, trying to access to the 10th element.
Passing the mouse over the line "array" here
cellValue = [array objectAtIndex:indexPath.row] ;
It tells me there are 9 objects on it, while there should be 45, as i declared them here, for the key #"Elementi":
- (void)viewDidLoad {
[super viewDidLoad];
listaOggetti = [[NSMutableArray alloc] init];
NSArray *arrayDesk = [NSArray arrayWithObjects: #"First",#"Second",#"Third"..#"9th", nil];
NSArray *sortedDesk = [arrayDesk sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSDictionary *dictDesk = [NSDictionary dictionaryWithObject:sortedDesk forKey:#"Elementi"];
NSArray *arrayLion = [NSArray arrayWithObjects:#"First1",#"Second1" ... #"30th", nil];
NSArray *sortedLion = [arrayLion sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSDictionary *dictLion = [NSDictionary dictionaryWithObject:sortedLion forKey:#"Elementi"];
NSArray *arrayRestore = [NSArray arrayWithObjects:#"First2",#"Second2" ... #"6th", nil];
NSArray *sortedRestore = [arrayRestore sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSDictionary *dictRest = [NSDictionary dictionaryWithObject:sortedRestore forKey:#"Elementi"];
[listaOggetti addObject:dictDesk];
[listaOggetti addObject:dictLion];
[listaOggetti addObject:dictRest];
copyListOfItems = [[NSMutableArray alloc] init];
self.navigationItem.title = NSLocalizedString(#"TIPS", #"Tips");
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"window.png"]];
//Add the search bar
self.tableView.tableHeaderView = searchBar;
searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
searching = NO;
letUserSelectRow = YES;
CGRect bounds = self.tableView.bounds;
bounds.origin.y = bounds.origin.y + searchBar.bounds.size.height;
self.tableView.bounds = bounds;
}
Shouldn't it see all the object for the key #"Elementi"? I'm on it from days, i can't understand how to solve, though.
Any help appreciated
*EDIT *
I noticed that
NSDictionary *dict = [listaOggetti objectAtIndex:indexPath.section];
has only 9 elements, as well as in the first array, but i have 3 dictionaries: dictDesk, dictLion, dictRest.
How can i do to select all the 45 elements in the NSDictionary?
*EDIT 2 *
Thanks to pengOne, i finally filled a global array with my 45 elements,this way
NSMutableArray *allObjects = [[NSMutableArray alloc] init];
[allObjects addObjectsFromArray:[[listaOggetti objectAtIndex:0] objectForKey:#"Elementi"]];
[allObjects addObjectsFromArray:[[listaOggetti objectAtIndex:1] objectForKey:#"Elementi"]];
[allObjects addObjectsFromArray:[[listaOggetti objectAtIndex:2] objectForKey:#"Elementi"]];
Now all i need to do it's to adapt something like this
NSDictionary *dictionary =[listaOggetti objectAtIndex:indexPath.row];
NSArray *array = [dictionary objectForKey:#"Elementi"];
cellValue = [array objectAtIndex:indexPath.row];
to the global array i've done, so it can let me search and select contents, either from tableView and SearchView.
The error tells you that you are sending this message:
[array objectAtIndex:9];
when array has 9 object, and it only responds to
[array objectAtIndex:0];
...
[array objectAtIndex:8];
The lines you need to investigate are:
NSArray *array = [dictionary objectForKey:#"Elementi"];
selectedRow = [array objectAtIndex:indexPath.row];
Check [dictionary objectForKey:#"Elementi"]. It appears to be an NSArray with 9 objects, when it needs to be an NSArray with at least 10 objects in order to access the object at index 10.
For your viewDidLoad method, it looks to me like listaOggetti is an NSMutableArray with 3 objects: dictDesk has 9 elements, dictLion has 30 elements, and dictRest has 6 elements.
To fix this error, you will need to change the number of rows in section 0 to be 9, the number of rows in section 1 to be 30 and the number of rows in section 2 to be 6.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString* cellValue=#"";
if (searching)
cellValue = [copyListOfItems objectAtIndex:indexPath.row];
else{
NSDictionary *dictionary = [listaOggetti objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"Elementi"];
cellValue = [array objectAtIndex:indexPath.row];
}
if ([cellValue isEqual: #"Apps on specific Desks"] || [cellValue isEqual: #"Applicazioni su più Scrivanie"]){
AppsViewController *appsController = [[AppsViewController alloc] initWithNibName:#"AppsViewController" bundle:nil];
[self.navigationController pushViewController:appsController animated:YES];
[appsController release];
}
}