UITableView gets Slower with every new NSMutableArray - ios

I have a UITableView that populates the results of a search that the user looks up. In order to do this I am using a NSMutableArray of Dictionaries where objects are added for the first 10, and then when the user scrolls to the bottom it populates the next 10 until there are no results left to show.
This all works well and good but I started to notice that the more searches that are done, the slower the table gets. Here is some of the code:
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self.objectsArray removeAllObjects];
[self.objectsArray setArray:nil];
[itemsTable reloadData];
[itemsTable scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:false];
[self loadItemsFromURL:searchURL withItemDescription:encodedString atStartRow:start andEndRow:end];
}
The above is when a new search is performed. It then does a NSURLConnection and responds with this:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (self.objectsArray == nil)
self.objectsArray = [NSMutableArray array];
// self.objectsArray = [[NSMutableArray alloc] init];
NSError *error;
NSDictionary *returnArray = [[NSJSONSerialization JSONObjectWithData:itemsData options:kNilOptions error:&error] valueForKey:#"items"];
for (id key in returnArray)
{
[self.objectsArray addObject:[returnArray objectForKey:key]];
}
counter += 10;
[itemsTable reloadData];
}
As you can see, if a user conducts a new search all objects are removed with [self.objectsArray removeAllObjects]and I even try to set the array to nil. If I perform multiple searches the UITableView gets slower and slower with scrolling each time. It is almost like the controller sees the array as getting larger and larger with each search even though I am removing all of the objects from it before the search. Any ideas or am I going about this the wrong way?
EDIT:
Here is the cellForRowAtIndexPath: method. cell is a subclassed UITableViewCell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Product Cell";
static NSString *LoadCellIdentifier = #"Loading Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if ([self.objectsArray count] <= 0 )
{
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.itemName.text = #"No items found.";
cell.itemPrice.text = #"";
cell.itemLocation.text = #"";
cell.addButton.hidden = YES;
}
else
{
if ([indexPath row] == [self.objectsArray count])
{
if ( [self.objectsArray count] >= 10 )
{
if ( [self.objectsArray count] < counter)
{
cell = [tableView dequeueReusableCellWithIdentifier:LoadCellIdentifier];
[cell.loadingSpinner stopAnimating];
cell.itemName.text = #"No more items found.";
}
else
{
if (!running)
{
[self loadItemsFromURL:searchURL withItemDescription:encodedString atStartRow:[self.objectsArray count] + 1 andEndRow:[self.objectsArray count] + 10];
cell = [tableView dequeueReusableCellWithIdentifier:LoadCellIdentifier];
cell.itemName.text = #"Loading more items...";
[cell.loadingSpinner startAnimating];
running = true;
}
else
{
cell = [tableView dequeueReusableCellWithIdentifier:LoadCellIdentifier];
[cell.loadingSpinner startAnimating];
}
}
}
}
else
{
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSArray *match = [self.objectsArray objectAtIndex:[indexPath row]];
cell.addButton.hidden = NO;
if ([match valueForKey:#"DESCRIPTION"] == [NSNull null] )
{
cell.itemName.text = #"Description not available.";
}
else
{
cell.itemName.text = [match valueForKey:#"DESCRIPTION"];
}
if ([match valueForKey:#"AD"] != [NSNull null])
{
NSMutableString *adString = [NSMutableString stringWithString:[match valueForKey:#"AD"]];
NSRange textRange;
textRange = [adString rangeOfString:#"1/"];
if (textRange.location != NSNotFound)
{
[adString replaceCharactersInRange:[adString rangeOfString:#"1/"] withString:#"$"];
}
else
{
[adString replaceCharactersInRange:[adString rangeOfString:#"/"] withString:#"/$"];
}
cell.itemPrice.text = adString;
}
else if ([match valueForKey:#"REGULAR"] == [NSNull null])
{
cell.itemPrice.text = #"$ N/A";
}
else
{
NSNumberFormatter *currencyStyle = [[NSNumberFormatter alloc] init];
[currencyStyle setFormatterBehavior:NSNumberFormatterBehavior10_4];
[currencyStyle setNumberStyle:NSNumberFormatterCurrencyStyle];
NSNumber *price = [NSNumber numberWithDouble:[[match valueForKey:#"REGULAR"] doubleValue]];
NSString *stringPrice = [currencyStyle stringFromNumber:price];
cell.itemPrice.text = [NSString stringWithFormat:#"%#", stringPrice];
}
if ([match valueForKey:#"AISLE"] == [NSNull null])
{
cell.itemLocation.text = #"Item location: N/A";
}
else
{
cell.itemLocation.text = [NSString stringWithFormat:#"Item Location: %#", [match valueForKey:#"AISLE"]];
}
match = nil;
}
}
return cell;
}
EDIT 2:
Here is a snippet of what the JSON looks like:
{
items = {
263149 = {
AD = "###";
AISLE = 6A;
DESCRIPTION = "Cinnamon Toasters";
R = 9;
REGULAR = "#.##";
};
26599 = {
AD = "####";
AISLE = 6A;
DESCRIPTION = "Quaker Life Cereal";
R = 2;
REGULAR = "#.##";
};
40517 = {
AD = "###";
AISLE = 6A;
DESCRIPTION = "Toasted Oats";
R = 1;
REGULAR = "#.##";
};
};
};

Ok, I think your problem is the excessive creation of Array objects. So do the following instead of you're array creation:
NSDictionary *returnArray = [[NSJSONSerialization JSONObjectWithData:itemsData options:kNilOptions error:&error] valueForKey:#"items"];
for (NSDictionary *dict in returnArray in returnArray)
{
[self.objectsArray addObject:dict];
}
counter += 10;
[itemsTable reloadData];
What you'll get as you see is an array of NSDictionary objects, your return array is already an NSDictionary of dictionary objects. Also, slight observation, where are you resetting your counter?
EDIT: creating the NSDictionary from NSData:
[NSJSONSerialization JSONObjectWithData:self.requestData options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error]
The requestData is generated using these delegate methods:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"In didReceiveResponse");
[self.requestData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"In didReceiveData");
[self.requestData appendData:data];
}

I was able to find the issue in one line in the cellForRowAtIndexPath:. I commented out: cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; at the top and made sure it was only called once. I also did do a bit of cleanup as suggested by 8vius and now only once NSString is being allocated in that method call. Once I did these two things it was nice and responsive again without any stutters.

Related

UICollectionViewCell one of the section from UICollectionView Cell Repeating same cell for multiple times

I have an old project done by a developer some times ago.. This particular project has 3 collection views such as collectionAnnouncments, collectionNews and collectionBulletin.
The first collectionview collectionAnnouncments is loading a same cell 10 times. But other two sections loading the cell correctly one time as per the response count.
I don't have any idea up to now for this problem. I tried some solutions from the google but I couldn't sorted because of the bad UI and Code implementation by that developer.
Ex- He used one UICollectionView Inside a tableview and using UICollectionView Class for all 3 collectionview and used a general cell for all collectionviews.
declaration... in m file
__weak IBOutlet UITableView *table;
UICollectionView *collectionAnnouncments, *collectionBulletin,
*collectionNews;
Please check the following codes and provide me a better simple solution to fix this issue without any major modifications or re-implementation because I don't have time for that.
- (void)viewDidLoad {
[super viewDidLoad];
self.automaticallyAdjustsScrollViewInsets = NO;
home.title=[Utilities getLocalizedStringForKey:#"Home"];
[Utilities setNavigationController:self];
//self.label.text=NSLocalizedFailureReasonErrorKey
self.navigationItem.leftBarButtonItem = nil;
__block BOOL newsDone = NO, bulletInDone = NO, announcmentDone = NO, refreshed = NO;
collectionViewDic = [[NSMutableDictionary alloc]init];
[Utilities serverRequest:#{#"getNewsfeed":#"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {
collectionViewDic[#"news"] = response[#"response"];
NSArray *responseValues = [response[#"response"] allValues]; // An NSArray of NSArrays
NSMutableArray *dictionarys = [NSMutableArray new];
for (NSArray *dictArrays in responseValues) {
for (NSDictionary *dict in dictArrays) {
[dictionarys addObject:dict];
}
}
_newsArray = dictionarys;
NSLog(#"news%#",dictionarys);
// sorting to newest
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"nf_id" ascending:NO];
_sortednewsArray = [_newsArray sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"Sorted news Response -%#", _sortednewsArray);
//Registeriing the collectionview custom cell
// [UICollectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:#"customCell"];
// [collectionAnnouncments registerClass:[CustomCell class] forCellWithReuseIdentifier:#"customCell"];
// [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"Cell"];
newsDone = YES;
if (newsDone && bulletInDone && announcmentDone && !refreshed) {
refreshed = YES;
[table reloadData];
}
} errorBlock:nil];
[Utilities serverRequest:#{#"getBulletin":#"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {
// NSString *bulletinID = #"wb_id";
collectionViewDic[#"bulletin"] = response[#"response"];
NSArray *responseValues = [response[#"response"] allValues]; // An NSArray of NSArrays
NSMutableArray *dictionarys = [NSMutableArray new];
for (NSArray *dictArrays in responseValues) {
for (NSDictionary *dict in dictArrays) {
[dictionarys addObject:dict];
}
}
_bulletinArray = dictionarys;
NSLog(#"bulletin%#",dictionarys);
// sorting to newest
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"wb_id" ascending:NO];
_sortedbulletinArray = [_bulletinArray sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"Sorted bulletin Response -%#", _sortedbulletinArray);
bulletInDone = YES;
if (newsDone && bulletInDone && announcmentDone && !refreshed) {
refreshed = YES;
[table reloadData];
}
} errorBlock:nil];
[Utilities serverRequest:#{#"getAnnouncement":#"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {
collectionViewDic[#"announcement"] = response[#"response"];
NSArray *responseValues = [response[#"response"] allValues]; // An NSArray of NSArrays
NSMutableArray *dictionarys = [NSMutableArray new];
for (NSArray *dictArrays in responseValues) {
for (NSDictionary *dict in dictArrays) {
[dictionarys addObject:dict];
}
}
_annArray = dictionarys;
NSLog(#"AnnouncementResponse%#",dictionarys);
NSLog(#" Ann ID%#", [dictionarys valueForKey:#"anc_id"]);
// sorting to newest
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"date_added" ascending:NO];
_sortedAnnArray = [_annArray sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"Sorted Array Response -%#", _sortedAnnArray);
NSLog(#"Sorted Ann Array-count%zd",_sortedAnnArray.count);
NSLog(#"Sorted Ann ID%#", [_sortedAnnArray valueForKey:#"anc_id"]);
announcmentDone = YES;
if (newsDone && bulletInDone && announcmentDone && !refreshed) {
refreshed = YES;
[table reloadData];
}
} errorBlock:nil];
menuView = [Utilities addMenuView:self];
}
-(void)getNewsFeed
{
collectionViewDic = [[NSMutableDictionary alloc]init];
[Utilities serverRequest:#{#"getNewsfeed":#"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {
if(response != nil)
{
if ([response isKindOfClass:[NSString class]]) {
// print response .
NSLog(#"MAIN RESPONSE!%#",response);
}
//on successfully response, which provided dictionary,
else if ([[response objectForKey:#"success"] boolValue] == true) {
// on true print response data.
collectionViewDic[#"news"] = response[#"response"];
NSArray *responseValues = [response[#"response"] allValues]; // An NSArray of NSArrays
NSMutableArray *dictionarys = [NSMutableArray new];
for (NSArray *dictArrays in responseValues) {
for (NSDictionary *dict in dictArrays) {
[dictionarys addObject:dict];
}
}
_newsArray = dictionarys;
NSLog(#"news%#",dictionarys);
// sorting to newest
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"nf_id" ascending:NO];
_sortednewsArray = [_newsArray sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"Sorted news Response -%#", _sortednewsArray);
}
//on success response, with failure message which is false.
else if ([[response objectForKey:#"success"] boolValue] == false) {
// handle error on success is false.
}
}
} errorBlock:nil];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
#try {
NSString *key = #"";
if ([collectionView isEqual:collectionNews])
key = #"news";
else if ([collectionView isEqual:collectionAnnouncments])
key = #"announcement";
else if ([collectionView isEqual:collectionBulletin])
key = #"bulletin";
NSDictionary *mainDic = collectionViewDic[key];
NSArray *array = mainDic[ [mainDic allKeys][0] ];
return [array count];
} #catch (NSException *exception) {
return 0;
}
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
#try {
//NSString *key = #"";
if ([collectionView isEqual:collectionNews])
return _sortednewsArray.count;
else if ([collectionView isEqual:collectionAnnouncments])
return _sortedAnnArray.count;
else if ([collectionView isEqual:collectionBulletin])
return _sortedbulletinArray.count;
}
#catch (NSException *exception) {
return 0;
}
// return _sortedAnnArray.count + _sortednewsArray.count + _sortedbulletinArray.count;
// return [[collectionViewDic allKeys] count];
// return 50;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"generalCell" forIndexPath:indexPath];
// CustomCell *cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"customCell" forIndexPath:indexPath];
// cell.tag = indexPath.row;
[cell setTag:indexPath.row];
//UILabel *test = [cell.contentView viewWithTag:1];
UIImageView *image = [cell.contentView viewWithTag:1];
//UILabel *cellTitle = [cell.contentView viewWithTag:2];
//UILabel *cellHead =[cell.contentView viewWithTag:2];
if ([collectionView isEqual:collectionAnnouncments]) {
// NSDictionary *mainDic = collectionViewDic[#"announcement"];
// NSArray *array = mainDic[ [mainDic allKeys][indexPath.section] ];
NSDictionary *dic = _sortedAnnArray[indexPath.section] ;
collectionAnnouncments.delegate = self;
collectionAnnouncments.dataSource = self;
// cellHead.text =#"Announcements";
//cellTitle.text = dic[#"anc_title"];
if ([dic[#"announcement_images"] count] > 0)
[image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",ANNOUNCMENT_IMAGES_URL,dic[#"announcement_images"][0][#"wi_image"] ] ]] ;
}
else if([collectionView isEqual:collectionNews]) {
//cellHead.text =#"News";
// NSDictionary *mainDic = collectionViewDic[#"news"];
// NSArray *array = mainDic[ [mainDic allKeys][0] ];
NSDictionary *dic = _sortednewsArray[indexPath.section] ;
collectionNews.delegate = self;
collectionNews.dataSource = self;
//cellTitle.text = dic[#"nf_title"];
if ([dic[#"newsfeed_images"] count] > 0)
[image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",NEWS_IMAGES_URL,dic[#"newsfeed_images"][0][#"wi_image"] ] ]] ;
}
else if([collectionView isEqual:collectionBulletin]) {
// NSDictionary *mainDic = collectionViewDic[#"bulletin"];
// NSArray *array = mainDic[ _sortedbulletinArray[indexPath.section] ];
NSDictionary *dic = _sortedbulletinArray[indexPath.section] ;
collectionBulletin.delegate = self;
collectionBulletin.dataSource = self;
// cellTitle.text = dic[#"wb_title"];
if ([dic[#"bulletin_images"] count] > 0)
if ([dic[#"bulletin_images"][0][#"wi_type"] isEqualToString:#"video"]) {
[image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BULLETIN_IMAGES_URL,dic[#"ws_thumb"] ] ]] ;
}
else{
[image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BULLETIN_IMAGES_URL,dic[#"bulletin_images"][0][#"wi_image"] ] ]] ;
}
}
return cell;
}
#pragma mark UITableView Delegate, DataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 195.0f;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[collectionViewDic allKeys] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"tableCell"];
cell.tag = indexPath.row;
UICollectionView *c = [cell.contentView viewWithTag:111];
//c.scrollEnabled = NO;
UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
flow.minimumLineSpacing = flow.minimumInteritemSpacing = 0.0f;
flow.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width/1, c.bounds.size.height);
flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
// c.collectionViewLayout = flow;
UIView *header = [cell.contentView viewWithTag:1];
UIImageView *headerImage = [header viewWithTag:2];
UILabel *headerTitle = [header viewWithTag:3];
//NSLog(cell.tag);
switch (indexPath.row) {
case 0:
//NSLog(#"text");
headerImage.image = [UIImage imageNamed:#"Announcemets"];
//headerTitle.text = #"Announcments";
headerTitle.text=[Utilities getLocalizedStringForKey:#"Announcement"];
// NSLog(headerTitle.text);
collectionAnnouncments = c;
[collectionAnnouncments setCollectionViewLayout:flow];
collectionAnnouncments.delegate = self;
collectionAnnouncments.dataSource = self;
[collectionAnnouncments reloadData];
// NSLog(#"text");
break;
case 1:
headerImage.image = [UIImage imageNamed:#"News"];
headerTitle.text=[Utilities getLocalizedStringForKey:#"Business Highlight"];
collectionNews = c;
[collectionNews setCollectionViewLayout:flow];
collectionNews.delegate = self;
collectionNews.dataSource = self;
[collectionNews reloadData];
//NSLog(#"text");
break;
case 2:
headerImage.image = [UIImage imageNamed:#"Bulletin"];
headerTitle.text=[Utilities getLocalizedStringForKey:#"Bulletin Board"];
collectionBulletin = c;
[collectionBulletin setCollectionViewLayout:flow];
collectionBulletin.delegate = self;
collectionBulletin.dataSource = self;
[collectionBulletin reloadData];
//NSLog(#"text");
break;
default:
break;
}
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.destinationViewController isKindOfClass:[NewsListing class]]) {
NewsListing *c = segue.destinationViewController;
NSInteger row = ((UIButton *)sender).superview.superview.superview.tag;
if (row == 0) {
c.isAnnouncement = YES;
c.listingArray = collectionViewDic[#"announcement"];
}
else if (row == 1) {
c.isNews = YES;
c.listingArray = collectionViewDic[#"news"];
}
else if (row == 2) {
c.isBulletin = YES;
c.listingArray = collectionViewDic[#"bulletin"];
}
}
if ([segue.destinationViewController isKindOfClass:[NewsDetail class]]) {
NewsDetail *c = segue.destinationViewController;
UICollectionViewCell *cell = sender;
NSInteger row = ((UIButton *)sender).superview.superview.superview.tag;
if (row == 0) {
c.isAnnouncement = YES;
// NSDictionary *months = collectionViewDic[#"announcement"];
NSIndexPath *indexPath = [collectionAnnouncments indexPathForCell:cell];
// NSArray *month = months[[months allKeys][0] ];
NSArray *month = _sortedAnnArray;
c.detailDic = month[indexPath.section ];
}
else if (row == 1) {
c.isNews = YES;
// NSDictionary *months = collectionViewDic[#"news"];
NSIndexPath *indexPath = [collectionNews indexPathForCell:cell];
// NSArray *month = months[[months allKeys][0] ];
NSArray *month = _sortednewsArray;
c.detailDic = month[indexPath.section ];
}
else if (row == 2) {
c.isBulletin = YES;
// NSDictionary *months = collectionViewDic[#"bulletin"];
NSIndexPath *indexPath = [collectionBulletin indexPathForCell:cell];
// NSArray *month = months[[months allKeys][0] ];
NSArray *month = _sortedbulletinArray;
c.detailDic = month[indexPath.section ];
}
}
}
#end

call NSString whit multiple parameters

I am a beginner and maybe it is a trivial question.
I have this method:
-(NSString *)getInfoFormediaItem:(MPMediaItemCollection *)list {
NSString *trackCount;
if ([list count] > 0) {
trackCount = [NSString stringWithFormat:NSLocalizedString(#"%lu Songs", #""), (unsigned long)[list count]];
} else if([list count] == 1) {
trackCount = [NSString stringWithFormat:NSLocalizedString(#"1 Song", #"")];
} else {
trackCount = [NSString stringWithFormat:NSLocalizedString(#"0 Song", #"") ];
}
return [NSString stringWithFormat:#"%#", trackCount];
}
I would like to call it here with a MPMediaItemCollection:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if( cell == nil )
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"cell"];
}
MPMediaQuery *playlistsQuery = [MPMediaQuery playlistsQuery];
NSArray *playl = [playlistsQuery collections];
MPMediaItem *rowItem = [playl objectAtIndex:indexPath.row];
MPMediaItemCollection * collection = [[MPMediaItemCollection alloc] initWithItems:[NSArray arrayWithObject:rowItem]];
cell.detailTextLabel.text = [self getInfoFormediaItem:collection];
}
I would like to get the number of tracks in each playlist.
It doesn't work. How do I fix? Thanks in advance!
Why are you using performSelector:withObject:? Just call the method directly:
cell.detailTextLabel.text = [self getInfoFormediaItem:collection];
Why are you passing nil to the withObject: parameter? That's why your code goes to the else. list is nil so [list count] will always be 0. You need to pass an actual instance of a MPMediaItemCollection.
Why are you needlessly using stringWithFormat: for the 1 and 0 count checks? Just do:
-(NSString *)getInfoFormediaItem:(MPMediaItemCollection *)list {
NSString *trackCount;
if ([list count] > 1) {
trackCount = [NSString stringWithFormat:NSLocalizedString(#"%lu Songs", #""), (unsigned long)[list count]];
} else if([list count] == 1) {
trackCount = NSLocalizedString(#"1 Song", #"");
} else {
trackCount = NSLocalizedString(#"0 Song", #"");
}
return trackCount;
}
Based on your updated question, your cellForRowAtIndexPath code isn't correct for the getting the media collection. The collectionsmethod returns an array of MPMediaCollection objects, not MPMediaItem objects. You need:
MPMediaQuery *playlistsQuery = [MPMediaQuery playlistsQuery];
NSArray *playl = [playlistsQuery collections];
MPMediaItemCollection *collection = playl[indexPath.row];
Now you can use collection when you call getInfoFormediaItem:.
You simply don't need to call this statement:
cell.detailTextLabel.text = [self performSelector:#selector(getInfoFormediaItem:) withObject:nil];
in your "getInfoFormediaItem"method. You do that in your "cellforrowataIndexPath" method when you define the cell,just call like this:
cell.detailTextLabel.text = [self getInfoFormediaItem:This_Is_A_List_You_Wanna_Pass_To_The_Method];
and you should be good to go.
In addition to the problems pointed out by other posters, your if statement will not work as you want it to:
if ([list count] > 0) {
trackCount = [NSString stringWithFormat:NSLocalizedString(#"%lu Songs",
#""), (unsigned long)[list count]];
} else if([list count] == 1) {
trackCount = [NSString stringWithFormat:NSLocalizedString(#"1 Song", #"")];
} else {
trackCount = [NSString stringWithFormat:NSLocalizedString(#"0 Song", #"") ];
}
The "if ... >0" clause will match first, before checking for a value of 1, since 1 is > 0. Thus the "if ... == 1" will never evaluate as true. You need to reorder that if statement:
if ([list count] == 1) {
trackCount = NSLocalizedString(#"1 Song", #"");
else if ([list count] > 0) {
trackCount = [NSString stringWithFormat:NSLocalizedString(#"%lu Songs",
#""), (unsigned long)[list count]];
}
else
{
trackCount = NSLocalizedString(#"0 Songs", #"");
}

How to apply a logic in UISearchBar to reload a table with new data?

Hi guys I need your help in my situation, I am working with UISearchBar and all the delegate method I already declared, but I don't know the logic to reload the table data with filtered array.
All the data in my table come from json.
This is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ChatListCell *cell=[tableView dequeueReusableCellWithIdentifier:#"contactListCell"];
if(!cell){
cell = [[ChatListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"contactListCell"];
}
if (issearching) {
ChatListData *chatlistdata = [filteredContentList objectAtIndex:indexPath.row];
}
NSLog(#"ceel %#", cell);
ChatListData *chatlistData = [chatList objectAtIndex:indexPath.row];
NSString *txtName = chatlistData.name;
NSLog(#"name %#", txtName);
NSData *emojiData = [txtName dataUsingEncoding:NSUTF8StringEncoding];
NSString *emojiTxtName = [[NSString alloc] initWithData:emojiData encoding:NSNonLossyASCIIStringEncoding];
cell.txtName.text = emojiTxtName;
cell.txtTime.text = chatlistData.time;
NSString *stringImg = #"image";
NSString *stringVideo = #"video";
if(![chatlistData.mime_type isEqual: [NSNull null]]){
if ([chatlistData.mime_type rangeOfString:stringImg].location == NSNotFound || [chatlistData.mime_type rangeOfString:stringVideo].location == NSNotFound) {
if ([chatlistData.mime_type rangeOfString:stringImg].location == NSNotFound) {
cell.txtMsg.text = #"Image";
}else if([chatlistData.mime_type rangeOfString:stringVideo].location == NSNotFound){
cell.txtMsg.text = #"Video";
}
This is my tabview code of cell index.
-(void)searchBar:(UISearchBar*)searchBar textDidChange: (NSString*)text
{
if(text.length == 0)
{
issearching = FALSE;
}
else
{
NSMutableArray *chatlitdata;
issearching= true;
NSLog(#"searching");
filteredContentList = [[NSMutableArray alloc] init];
filteredContentList = chatlitdata;
// if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound)
{
[filteredContentList addObject:chatList];
}
}

Parsing JSON to Table View error index (19) beyond bounds (19)

I'm parsing a JSON file to a table view in my iPhone app.
This is my code:
#import "DEMOSecondViewController.h"
#import "DEMONavigationController.h"
#import "PostsObject.h"
#import "RNBlurModalView.h"
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 10.0f
#define FONT_SIZE 14.0f
#interface DEMOSecondViewController ()
{
NSInteger refreshIndex;
NSArray *fbPost;
NSArray *pic;
NSArray *published;
}
#end
#implementation DEMOSecondViewController
#synthesize tweets;
#synthesize changeData;
- (void)refreshChannels:(id)sender {
if (tweets.count == 0) return;
// disable UI
self.title = #"Updating...";
self.navigationController.view.userInteractionEnabled = YES;
refreshIndex = 0;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Posts";
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Menu"
style:UIBarButtonItemStylePlain
target:(DEMONavigationController *)self.navigationController
action:#selector(showMenu)];
self.myTableView.separatorColor = [UIColor clearColor];
changeData.selectedSegmentIndex = 0;
[changeData addTarget:self action:#selector(segmentedControlSelectedIndexChanged:) forControlEvents:UIControlEventValueChanged];
[self issueLoadRequest];
}
- (void)segmentedControlSelectedIndexChanged:(id)sender
{
[self issueLoadRequest];
}
#pragma mark - Table view data source
- (void)issueLoadRequest
{
if (changeData.selectedSegmentIndex == 0) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"website.php"]];
[self performSelectorOnMainThread:#selector(receiveData:) withObject:data waitUntilDone:YES];
});
} else if (changeData.selectedSegmentIndex == 1){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"website.php"]];
[self performSelectorOnMainThread:#selector(receiveData:) withObject:data waitUntilDone:YES];
});
} else if (changeData.selectedSegmentIndex == 2) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"website.php"]];
[self performSelectorOnMainThread:#selector(receiveData:) withObject:data waitUntilDone:YES];
});
}
}
- (void)receiveData:(NSData *)data {
if (changeData.selectedSegmentIndex == 0) {
self.tweets = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[self.myTableView reloadData];
} else if (changeData.selectedSegmentIndex == 1) {
self.tweets1 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[self.myTableView reloadData];
} else if (changeData.selectedSegmentIndex == 2) {
self.tweets2 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[self.myTableView reloadData];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (changeData.selectedSegmentIndex == 0) {
return self.tweets.count;
} else if (changeData.selectedSegmentIndex == 1) {
return self.tweets1.count;
} else {
return self.tweets2.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"PostsObject";
// The element in the array is going to be a dictionary. I JUST KNOW THIS. The key for the tweet is "text".
NSDictionary *tweet = [self.tweets objectAtIndex:indexPath.row];
NSDictionary *tweet1 = [self.tweets1 objectAtIndex:indexPath.row];
NSDictionary *tweet2 = [self.tweets2 objectAtIndex:indexPath.row];
PostsObject *cell = (PostsObject *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"PostsObject" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (changeData.selectedSegmentIndex == 0) {
cell.fbPost.text = [tweet objectForKey:#"message"];
cell.published.text = [tweet objectForKey:#"published"];
cell.pic.image = [UIImage imageNamed:#"facebook_icon.png"];
} else if (changeData.selectedSegmentIndex == 1) {
cell.fbPost.text = [tweet1 objectForKey:#"tweet"];
cell.published.text = [tweet1 objectForKey:#"posted"];
cell.pic.image = [UIImage imageNamed:#"twitter_icon.png"];
} else if (changeData.selectedSegmentIndex == 2) {
cell.fbPost.text = [tweet2 objectForKey:#"message"];
cell.published.text = [tweet objectForKey:#"published"];
cell.pic.image = [UIImage imageNamed:#"twitter_icon.png"];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 96;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (changeData.selectedSegmentIndex == 0) {
//Öppna länken eller liknande
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
NSString * storyLink = [[tweets objectAtIndex: storyIndex] objectForKey:#"message"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];
RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:#"Message" message:storyLink];
[modal show];
// Spit out some pretty JSON for the tweet that was tapped. Neato.
NSString *formattedJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:[self.tweets objectAtIndex:indexPath.row] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
NSLog(#"tweet:\n%#", formattedJSON);
} else if (changeData.selectedSegmentIndex == 1) {
//Öppna länken eller liknande
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
NSString * tweetLink = [[tweets objectAtIndex: tweetLink] objectForKey:#"tweet"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:tweetLink]];
RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:#"Message" message:tweetLink];
[modal show];
// Spit out some pretty JSON for the tweet that was tapped. Neato.
NSString *formattedJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:[self.tweets objectAtIndex:indexPath.row] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
NSLog(#"tweet:\n%#", formattedJSON);
} else if (changeData.selectedSegmentIndex == 2) {
//Öppna länken eller liknande
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
NSString * storyLink = [[tweets objectAtIndex: storyIndex] objectForKey:#"message"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];
RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:#"Message" message:storyLink];
[modal show];
// Spit out some pretty JSON for the tweet that was tapped. Neato.
NSString *formattedJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:[self.tweets objectAtIndex:indexPath.row] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
NSLog(#"tweet:\n%#", formattedJSON);
}
}
#end
When I launch the app I see that it parses the data correct to the table view. But when I begin to scroll down in the list the app crashes and gives me this strange error:
Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (19) beyond bounds (19)
Can someone please help me with this?
You shouldn't do this:
// The element in the array is going to be a dictionary. I JUST KNOW THIS. The key for the tweet is "text".
NSDictionary *tweet = [self.tweets objectAtIndex:indexPath.row];
NSDictionary *tweet1 = [self.tweets1 objectAtIndex:indexPath.row];
NSDictionary *tweet2 = [self.tweets2 objectAtIndex:indexPath.row];
because you can't guarantee that all of the arrays have the same number of items in them. Check your configuration attribute (selectedSegmentIndex) before trying to access only the appropriate array.

IndexPath.row changes when using search issue?

I am trying to successfully implement a UISearchcontroller into my UITableview however I have the following issues, I pass data using the indexPath.row method to the next view controller and the indexPath.row changes when I search, secondly I am using multiple arrays for my data in my tableview, and so what i've done is created another array that holds all of the other arrays content in one and searches through that, and it all works perfectly except when I want to pass my data because the indexPath.row changes instead of staying with the cell (which is what i need to happen). Please could you check out my code and see if you can help?
#import "AbsViewController.h"
#interface AbsViewController ()
#end
#implementation AbsViewController {
//these are all my arrays
//The arrays that carry for no equipment.
NSArray *tableData;
NSArray *thumbnails;
NSArray *sets;
NSArray *reps;
NSArray *instructions;
NSArray *materials;
NSArray *status;
NSArray *tips;
NSArray *difficulty;
NSArray *target;
//The arrays that carry for equipment.
NSArray *tableData1;
NSArray *thumbnails1;
NSArray *sets1;
NSArray *reps1;
NSArray *instructions1;
NSArray *materials1;
NSArray *status1;
NSArray *tips1;
NSArray *difficulty1;
NSArray *target1;
//The arrays that carry for bosu ball.
NSArray *tableData2;
NSArray *thumbnails2;
NSArray *sets2;
NSArray *reps2;
NSArray *instructions2;
NSArray *materials2;
NSArray *status2;
NSArray *tips2;
NSArray *difficulty2;
NSArray *target2;
//The arrays that carry for physio ball.
NSArray *tableData3;
NSArray *thumbnails3;
NSArray *sets3;
NSArray *reps3;
NSArray *instructions3;
NSArray *materials3;
NSArray *status3;
NSArray *tips3;
NSArray *difficulty3;
NSArray *target3;
//The arrays that carry for weighted.
NSArray *tableData4;
NSArray *thumbnails4;
NSArray *sets4;
NSArray *reps4;
NSArray *instructions4;
NSArray *materials4;
NSArray *status4;
NSArray *tips4;
NSArray *difficulty4;
NSArray *target4;
//Search array
NSArray *tableData5;
NSArray *status5;
NSArray *thumbnails5;
//The array for the search results.
NSArray *searchResults;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Abdominal";
//Here im initializing my arrays.
// Find out the path of my array.
NSString *path = [[NSBundle mainBundle] pathForResource:#"Abs" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
tableData = [dict objectForKey:#"name"];
thumbnails = [dict objectForKey:#"imageFile"];
status = [dict objectForKey:#"status"];
// Find out the path of recipes.plist
NSString *path1 = [[NSBundle mainBundle] pathForResource:#"Abs1" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict1 = [[NSDictionary alloc] initWithContentsOfFile:path1];
tableData1 = [dict1 objectForKey:#"name"];
thumbnails1 = [dict1 objectForKey:#"imageFile"];
status1 = [dict1 objectForKey:#"status"];
// Find out the path of recipes.plist
NSString *path2 = [[NSBundle mainBundle] pathForResource:#"Abs2" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict2 = [[NSDictionary alloc] initWithContentsOfFile:path2];
tableData2 = [dict2 objectForKey:#"name"];
thumbnails2 = [dict2 objectForKey:#"imageFile"];
status2 = [dict2 objectForKey:#"status"];
// Find out the path of recipes.plist
NSString *path3 = [[NSBundle mainBundle] pathForResource:#"Abs3" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict3 = [[NSDictionary alloc] initWithContentsOfFile:path3];
tableData3 = [dict3 objectForKey:#"name"];
thumbnails3 = [dict3 objectForKey:#"imageFile"];
status3 = [dict3 objectForKey:#"status"];
NSString *path4 = [[NSBundle mainBundle] pathForResource:#"Abs4" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict4 = [[NSDictionary alloc] initWithContentsOfFile:path4];
tableData4 = [dict4 objectForKey:#"name"];
thumbnails4 = [dict4 objectForKey:#"imageFile"];
status4 = [dict4 objectForKey:#"status"];
//this is the array that carries all the content.
NSString *path5 = [[NSBundle mainBundle] pathForResource:#"AbsTotal" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict5 = [[NSDictionary alloc] initWithContentsOfFile:path5];
tableData5 = [dict5 objectForKey:#"name"];
status5 = [dict5 objectForKey:#"status"];
thumbnails5 = [dict5 objectForKey:#"thumbnails"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (self.searchDisplayController.isActive) {
return 1;
}
return 5 ;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResults count];
}
else if (section == 0) {
return [tableData count];
}
else if (section == 1) {
return [tableData1 count];
}
else if (section == 2) {
return [tableData2 count];
}
else if (section == 3) {
return [tableData3 count];
}
else if (section == 4) {
return [tableData4 count];
}
else {
return [tableData5 count];
}
}
//this is my cellForRowAtIndexPath method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"ExerciseCell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleTableIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
}
else if (indexPath.section == 0) {
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Type: %#", [status objectAtIndex:indexPath.row]];
cell.imageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
}
else if (indexPath.section == 1) {
cell.textLabel.text = [tableData1 objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Type: %#", [status1 objectAtIndex:indexPath.row]];
cell.imageView.image = [UIImage imageNamed:[thumbnails1 objectAtIndex:indexPath.row]];
}
else if (indexPath.section == 2) {
cell.textLabel.text = [tableData2 objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Type: %#", [status2 objectAtIndex:indexPath.row]];
cell.imageView.image = [UIImage imageNamed:[thumbnails2 objectAtIndex:indexPath.row]];
}
else if (indexPath.section == 3) {
cell.textLabel.text = [tableData3 objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Type: %#", [status3 objectAtIndex:indexPath.row]];
cell.imageView.image = [UIImage imageNamed:[thumbnails3 objectAtIndex:indexPath.row]];
}
else if (indexPath.section == 4) {
cell.textLabel.text = [tableData4 objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Type: %#", [status4 objectAtIndex:indexPath.row]];
cell.imageView.image = [UIImage imageNamed:[thumbnails4 objectAtIndex:indexPath.row]];
}
else {
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Type: %#", [status objectAtIndex:indexPath.row]];
cell.imageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
}
return cell;
}
//this is where i've attempted to fix the issue but didn't work.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger rowNumber = 0;
for (NSInteger i = 0; i < indexPath.section; i++) {
rowNumber += [self tableView:tableView numberOfRowsInSection:i];
}
rowNumber += indexPath.row;
NSLog(#"%ld",(long)rowNumber);
}
//this is where i filter my tableview
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF contains[cd] %#", searchText];
searchResults = [tableData5 filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
//Here i create my view for my header/
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
// create the parent view that will hold header Label
UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,25)];
customView.backgroundColor = [UIColor belizeHoleColor];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
headerLabel.backgroundColor = [UIColor belizeHoleColor];
headerLabel.font = [UIFont fontWithName:#"Avenir-Black" size:14];
headerLabel.frame = CGRectMake(6,0,320,25);
if (section == 1) {
headerLabel.text = #"";
}
if (section == 2) {
headerLabel.text = #"";
}
if (section == 3) {
headerLabel.text = #"";
}
if (section == 4) {
headerLabel.text = #"";
}
if (section == 0) {
headerLabel.text = #"";
}
headerLabel.textColor = [UIColor cloudsColor];
[customView addSubview:headerLabel];
return customView;
}
please if someone could help that would sooooooo appreciated.
thanks in advance.
//u can do this on - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath method first get
if (tableView == self.searchDisplayController.searchResultsTableView)
{
NSString *PassData = [tableData5 objectAtIndex:indexPath.row];
// NSString *passData = nil; //COMMENT THIS LINE SINCE IT CONTAINS SELECTED VALUE FROM SEARCH DISPLAY TABLEVIEW NO NEED TO BE ST NULL AGAIN "COMMENT THIS LINE AND TRY"
NSString *selectedStatus = nil;
UIImage *selectedThumbImage = nil;
//assuming ur array's contains equal number of objects
if([tableData containsObject:passData]) //if the search results contains an object in this array
{
//by using passData from search results tableview's tapped row u cn get all the below grouped tableview data now do for other array's
int index = [tableData indexOfObject:passData]; //get the index of selected array
selectedStatus = [status objectAtIndex:index]; //from that index get the status data
selectedThumbImage = [thumbnails objectAtIndex:index];//get thumbnil image from index
}
else if ([tableData1 containsObject:passData])
{
int index = [tableData1 indexOfObject:passData]; //get the index of selected array
selectedStatus = [status1 objectAtIndex:index]; //from that index get the status data
selectedThumbImage = [thumbnails1 objectAtIndex:index];//get thumbnil image from index
}
else if ([tableData2 containsObject:passData])
{
int index = [tableData2 indexOfObject:passData]; //get the index of selected array
selectedStatus = [status2 objectAtIndex:index]; //from that index get the status data
selectedThumbImage = [thumbnails2 objectAtIndex:index];//get thumbnil image from index
}
else if (//check for otehr remaining array)
{
//grab all details
}
//at the end your passData contains title , selectedStatus contains status , and selectedThumbImage contains thumb image use it to pass
}//end if (tableView == self.searchDisplayController.searchResultsTableView)

Resources