Setting cell.textlabel.text from json array - objective-c

Hello I'm trying to parse data from json and get the values to show in cells.
Here is my ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{
IBOutlet UITableView *mainTableView;
NSMutableData *data;
}
#property (nonatomic, strong) NSArray *category;
#property (nonatomic, strong) NSArray *coursesArray;
#property (nonatomic, strong) NSDictionary *parsedData;
#end
This is what I have in ViewController.m
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
parsedData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
coursesArray = [parsedData valueForKey:#"courses"];
NSLog(#"coursesArray: %#", coursesArray);
category = [coursesArray valueForKey:#"category"];
NSLog(#"%#", category);
}
-(int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MainCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"MainCell"];
}
cell.textLabel.text = [NSString stringWithFormat:#"%#", [category objectAtIndex:indexPath.row]];
NSLog(#"%#", category);
return cell;
}
At connectionDidFinishLoading I see in the log the right values, but when I try to check them before the cell is created I get null.
What I'm doing wrong here?

Call
[mainTableView reloadData];
inside your -connectionDidFinishLoading: method.

Make sure your category array is not released/autoreleased.

Related

Using TouchesBegan in my TableViewController

Good afternoon,
I would like to tap the profile image (like Facebook app) inside a row in my TableViewController using "TouchesBegan" to display a new ViewController with more information regarding the user. That means going from TableViewController (touch in the image of the TableViewCell) and then go (segue) to another ViewController called "ProfileViewController".
When I tried to do that directly in my TableViewCell it didn't worked because it's not a ViewController (it's a subclass of TableViewController) so I cannot move to a different ViewController from that.
So, what I'm trying to do now, is create a TouchesBegan in the UIImage from my TableViewController, but I get a warning (and followed by a crash) because I use a NSArray to fill the UIImage URL and it seems that I cannot assign a TouchesBegan directly to the image.
Can you help me with more information or some example? Maybe there is something I'm missing because It's my first time trying to do something like that and any help will be appreciated.
Here you are my code:
That's my TableViewController:
//
// CarTableViewController.m
// TableViewStory
//
#import "CarTableViewController.h"
#import "CarTableViewCell.h"
#import "CarTableViewController.h"
#import "CarDetailViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#implementation CarTableViewController
#synthesize carMakes = _carMakes;
#synthesize carModels = _carModels;
#synthesize carImages = _carImages;
#synthesize likes = _likes;
#synthesize comments = _comments;
#synthesize username = _username;
#synthesize refuser = _refuser;
#synthesize profileImage = _profileImage;
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchJson];
[self.tableView reloadData];
// Initialize the refresh control.
self.refreshControl = [[UIRefreshControl alloc] init];
//self.refreshControl.backgroundColor = [UIColor blackColor];
//self.refreshControl.tintColor = [UIColor whiteColor];
[self.refreshControl addTarget:self
action:#selector(fetchJson)
forControlEvents:UIControlEventValueChanged];
}
- (void)viewWillAppear:(BOOL)animated
{
self.navigationController.navigationBar.hidden = YES;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [_jsonArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"carTableCell";
CarTableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CarTableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.makeLabel.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"id"];
cell.likes.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"likes"];
cell.comments.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"comments"];
cell.username.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"username"];
cell.refuser.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"user_ref"];
cell.modelLabel.text = [[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"user"];
NSURL * imageURL = [NSURL URLWithString:[[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"imagen"]];
[cell.carImage setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:#"imagen"] options:SDWebImageRefreshCached];
NSURL * imageURL2 = [NSURL URLWithString:[[_jsonArray objectAtIndex:indexPath.row] valueForKey:#"image"]];
[cell.profileImage setImageWithURL:imageURL2
placeholderImage:[UIImage imageNamed:#"image"]
options:SDWebImageRefreshCached];
return cell;
}
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
CGPoint pt = [[touches anyObject] locationInView:_profileImage];
if (pt.x>=0 && pt.x<=100 && pt.y>=0 && pt.y<=100)
{
[self performSegueWithIdentifier:#"ID" sender:self];
}
else
{
NSLog(#"image not touched");
}
}
/*
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"ShowCarDetails"])
{
CarDetailViewController *detailViewController = [segue destinationViewController];
NSIndexPath *myIndexPath = [self.tableView indexPathForSelectedRow];
detailViewController.carDetailModel = [[NSArray alloc]
initWithObjects:
[[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:#"date"],
[[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:#"id"],
[[_jsonArray objectAtIndex:[myIndexPath row]] valueForKey:#"imagen"],
nil];
}
}
*/
-(void)fetchJson {
self.carModels = [[NSMutableArray alloc] init];
self.carMakes = [[NSMutableArray alloc] init];
self.carImages = [[NSMutableArray alloc] init];
self.likes = [[NSMutableArray alloc] init];
self.comments = [[NSMutableArray alloc] init];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString * urlString = [NSString stringWithFormat:#"http://website.com/service.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSData * data = [NSData dataWithContentsOfURL:url];
NSError *error;
[_jsonArray removeAllObjects];
_jsonArray = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
for(int i=0;i<_jsonArray.count;i++)
{
NSDictionary * jsonObject = [_jsonArray objectAtIndex:i];
NSString* imagen = [jsonObject objectForKey:#"imagen"];
[_carImages addObject:imagen];
NSDictionary * jsonObject2 = [_jsonArray objectAtIndex:i];
NSString* user = [jsonObject2 objectForKey:#"user"];
[_carMakes addObject:user];
NSDictionary * jsonObject3 = [_jsonArray objectAtIndex:i];
NSString* date = [jsonObject3 objectForKey:#"date"];
[_carModels addObject:date];
}
NSLog(#"carModels ==> %#", _jsonArray);
dispatch_async(dispatch_get_main_queue(), ^{
{
[self.tableView reloadData];
[self.refreshControl endRefreshing];
}});
}
);
}
#end
And that's my TableViewController.h
//
// CarTableViewController.h
// TableViewStory
//
#import <UIKit/UIKit.h>
#interface CarTableViewController : UITableViewController
#property (nonatomic, strong) IBOutlet UITableView *tableView;
#property (nonatomic, strong) NSMutableArray *carImages;
#property (nonatomic, strong) NSMutableArray *carMakes;
#property (nonatomic, strong) NSMutableArray *carModels;
#property (nonatomic, strong) NSMutableArray *likes;
#property (nonatomic, strong) NSMutableArray *comments;
#property (nonatomic, strong) NSMutableArray *username;
#property (nonatomic, strong) NSMutableArray *refuser;
#property (nonatomic, strong) NSMutableArray *profileImage;
#property (nonatomic, strong) NSMutableArray *jsonArray;
#property (nonatomic, strong) IBOutlet UIImage *touchImageVIew;
#end
Thanks in advance.
If your UIImageView should act like a button, you should make it a UIButton instead of a UIImageView. With an UIButton you can set a segue in the Interface Builder. Here's an example of the UITableViewController:
class TableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
let dataSource = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
dataSource.addObject(UIImage(named: "image.jpg")!)
dataSource.addObject(UIImage(named: "image.jpg")!)
tableView.reloadData()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("tableviewcell", forIndexPath: indexPath) as TableViewCell
let image = dataSource.objectAtIndex(indexPath.row) as UIImage
cell.button.setBackgroundImage(image, forState: UIControlState.Normal)
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "pushtodetail" {
println("performing segue from a button in a cell")
}
}
}

UISearchBarDelegate on UITableView with Sections Issue

I'm having issues with implementing the UISearchBarDelegate on my UITableView with sections issue where every time I try to search for something inside the UITableView, either it doesn't display the desired result or it crashes the app with an error saying:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
Here's inside my header file:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate, UISearchBarDelegate>
{
UITableView *mainTableView;
NSMutableArray *contentsList;
NSMutableArray *searchResults;
NSString *savedSearchTerm;
NSMutableArray *ivSectionKeys;
NSMutableDictionary *ivSectionContents;
}
#property (nonatomic, retain) IBOutlet UITableView *mainTableView;
#property (nonatomic, retain) NSMutableArray *contentsList;
#property (nonatomic, retain) NSMutableArray *searchResults;
#property (nonatomic, copy) NSString *savedSearchTerm;
#property (nonatomic, retain) NSMutableArray *sectionKeys;
#property (nonatomic, retain) NSMutableDictionary *sectionContents;
- (void)handleSearchForTerm:(NSString *)searchTerm;
#end
while this is inside my implementation file:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize mainTableView;
#synthesize contentsList;
#synthesize searchResults;
#synthesize savedSearchTerm;
#synthesize sectionKeys = ivSectionKeys;
#synthesize sectionContents = ivSectionContents;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSMutableArray *keys = [[NSMutableArray alloc] init];
NSMutableDictionary *contents = [[NSMutableDictionary alloc] init];
NSString *colorKey = #"Colors";
NSString *clothingKey = #"Clothing";
NSString *miscKey = #"Misc";
[contents setObject:[NSArray arrayWithObjects:#"Red", #"Blue", nil] forKey:colorKey];
[contents setObject:[NSArray arrayWithObjects:#"Pants", #"Shirt", #"Socks", nil] forKey:clothingKey];
[contents setObject:[NSArray arrayWithObjects:#"Wankle Rotary Engine", nil] forKey:miscKey];
[keys addObject:clothingKey];
[keys addObject:miscKey];
[keys addObject:colorKey];
self.sectionKeys = keys;
self.sectionContents = contents;
// Restore search term
if (self.savedSearchTerm)
{
self.searchDisplayController.searchBar.text = self.savedSearchTerm;
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Save the state of the search UI so that it can be restored if the view is re-created.
self.savedSearchTerm = self.searchDisplayController.searchBar.text;
self.searchResults = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.mainTableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)handleSearchForTerm:(NSString *)searchTerm
{
self.savedSearchTerm = searchTerm;
if (self.searchResults == nil)
{
NSMutableArray *array = [[NSMutableArray alloc] init];
self.searchResults = array;
array = nil;
}
[self.searchResults removeAllObjects];
if ([self.savedSearchTerm length] != 0)
{
for (NSString *currentString in self.sectionContents)
{
if ([currentString rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound)
{
[self.searchResults addObject:currentString];
}
}
}
}
#pragma mark -
#pragma mark UITableViewDataSource Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger sections = [self.sectionKeys count];
return sections;
}
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section
{
NSString *key = [self.sectionKeys objectAtIndex:section];
return key;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
NSString *key = [self.sectionKeys objectAtIndex:section];
NSArray *contents = [self.sectionContents objectForKey:key];
NSInteger rows;
if (tableView == [[self searchDisplayController] searchResultsTableView])
rows = [self.searchResults count];
else
rows = [contents count];
NSLog(#"rows is: %d", rows);
return rows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *key = [self.sectionKeys objectAtIndex:indexPath.section];
NSArray *contents = [self.sectionContents objectForKey:key];
NSString *contentForThisRow = [contents objectAtIndex:indexPath.row];
if (tableView == [self.searchDisplayController searchResultsTableView])
contentForThisRow = [self.searchResults objectAtIndex:indexPath.row];
else
contentForThisRow = [contents objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = contentForThisRow;
return cell;
}
#pragma mark -
#pragma mark UITableViewDelegate Methods
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self handleSearchForTerm:searchString];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
self.savedSearchTerm = nil;
[self.mainTableView reloadData];
}
#end
I think my issue is inside my for-loop but I'm not really sure.
You need to update all of your table view data source and delegate methods to handle both tables (you only do this in some):
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger sections = [self.sectionKeys count];
return sections;
}
should be:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (tableView == self.tableView) {
NSInteger sections = [self.sectionKeys count];
return sections;
} else { // assume it's the search table
// replace this with the actual result
return numberOfSectionsForSearchTable;
}
}

Form sheet with custom split view like UITableView crash when scrolling

I have created a iPad app that has a settings form sheet. The form sheet is using two subviews for create a split view like display. The left (master) UITableView scrolls and launches fine. The error is coming in from when one of the master cells is selected and it displays a UITableView from a UITableViewController into the right(detail) view. It will display the UITableView but once it is scrolled the detail view crashes. Yes I have the list pulling from plist because I want these results be be accessed later in other places of the application.
this is the View Controller for the form sheet and delegate for Master View
.h file
#interface settingsViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>{
UITableView *mainTableView;
NSDictionary *mainSettingList;
NSArray *settingItems;
}
#property (weak, nonatomic) IBOutlet UINavigationBar *settingsNavigationBar;
#property (weak, nonatomic) IBOutlet UITableView *mainTableView;
#property (weak, nonatomic) IBOutlet UIView *borderView;
#property (strong, nonatomic) IBOutlet UIView *detailView;
.m file
#property (nonatomic, strong)NSDictionary *mainSettingList;
#property (nonatomic, strong)NSArray *settingItems;
#end
#implementation settingsViewController
#synthesize settingsNavigationBar = _settingsNavigationBar;
#synthesize mainTableView = _mainTableView;
#synthesize borderView = _borderView;
#synthesize settingItems, mainSettingList;
-(void)viewDidLoad{
[super viewDidLoad];
[self.detailView setFrame:CGRectMake(233, 0, 310, 620)];
[self.borderView setBackgroundColor:[UIColor lightGrayColor]];
[self.view addSubview:self.borderView];
[self.view addSubview:self.detailView];
}
- (IBAction)closePressed:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
-(NSDictionary *)mainSettingList{
if(!mainSettingList){
NSString *str_settingList = [[NSBundle mainBundle]pathForResource:#"settingsList" ofType:#"plist"];
mainSettingList = [NSDictionary dictionaryWithContentsOfFile:str_settingList];
self.mainSettingList = mainSettingList;
}
return mainSettingList;
}
-(NSArray *)settingItems{
if(!settingItems){
settingItems = [[self.mainSettingList allKeys]sortedArrayUsingSelector:#selector(compare:)];
self.settingItems = settingItems;
}
return settingItems;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.settingItems.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *wordsInSection = [self.mainSettingList objectForKey:
[self.settingItems objectAtIndex:section]];
return wordsInSection.count;
}
-(NSString *)nameAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *wordsInSection = [self.mainSettingList objectForKey:[self.settingItems objectAtIndex:indexPath.section]];
return [wordsInSection objectAtIndex:indexPath.row];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"AlumniListCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.textLabel.text = [self nameAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [self.settingItems objectAtIndex:section];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UINavigationController *nvc = [[UINavigationController alloc]init];
[nvc.view setFrame:CGRectMake(0,0, 310, 620)];
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
if([cellText isEqualToString:#"Types of Jumps"]){
TypesOfJumps *toj = [[TypesOfJumps alloc]initWithNibName:#"TypesOfJumps" bundle:nil];
[nvc pushViewController:toj animated:YES];
}
[self.detailView addSubview:nvc.view];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:#"You selected %#!", cellText] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
return YES;
}
- (void)viewDidUnload {
[self setSettingsNavigationBar:nil];
[self setBorderView:nil];
[self setMainTableView:nil];
[self setSubViewNavigaionBar:nil];
[self setDetailView:nil];
[super viewDidUnload];
}
#end
UITableViewController called by cell pressed method
.h file
#interface TypesOfJumps : UITableViewController<UITableViewDataSource,UITableViewDelegate>{
NSDictionary *listJumps;
NSArray *typesJumps;
}
#property (strong, nonatomic) IBOutlet UITableView *tableView;
.m file
#interface TypesOfJumps ()
#property (strong, nonatomic)NSDictionary *listJumps;
#property (strong, nonatomic)NSArray *typesJumps;
#end
#implementation TypesOfJumps
#synthesize listJumps = _listJumps;
#synthesize typesJumps = _typesJumps;
#synthesize tableView = _tableView;
-(NSDictionary *)listJumps{
if(!listJumps){
NSString *str_settingList = [[NSBundle mainBundle]pathForResource:#"TypesOfJumps" ofType:#"plist"];
listJumps = [NSDictionary dictionaryWithContentsOfFile:str_settingList];
self.listJumps = listJumps;
}
return listJumps;
}
-(NSArray *)typesJumps{
if(!typesJumps){
typesJumps = [[self.listJumps allKeys]sortedArrayUsingSelector:#selector(compare:)];
self.typesJumps = typesJumps;
}
return typesJumps;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return self.typesJumps.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *wordsInSection = [self.listJumps objectForKey:
[self.typesJumps objectAtIndex:section]];
return wordsInSection.count;
}
-(NSString *)nameAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *wordsInSection = [self.listJumps objectForKey:[self.typesJumps objectAtIndex:indexPath.section]];
return [wordsInSection objectAtIndex:indexPath.row];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"AlumniListCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.textLabel.text = [self nameAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [self.typesJumps objectAtIndex:section];
}

Simple twitter program not working

I'm using this tutorial to practice creating an extremely basic twitter app: http://www.codeproject.com/Articles/312325/Making-a-simple-Twitter-app-using-iOS-5-Xcode-4-2#setting-up-the-table-view
The only difference in my app is I'm only using tableView ViewController. I can't seem to get this to work.
ViewController.h
#interface ViewController : UIViewController {
NSArray *tweets;
}
-(void)fetchTweets;
#property (retain, nonatomic) IBOutlet UITableView *tableView;
#end
ViewController.m
#import "ViewController.h"
#import "Twitter/Twitter.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize tableView = _tableView;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self fetchTweets];
}
- (void)fetchTweets
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: #"https://api.twitter.com/1/statuses/public_timeline.json"]];
NSError* error;
tweets = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return tweets.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TweetCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
NSString *text = [tweet objectForKey:#"text"];
NSString *name = [[tweet objectForKey:#"user"] objectForKey:#"name"];
cell.textLabel.text = text;
cell.detailTextLabel.text = [NSString stringWithFormat:#"by %#", name];
return cell;
}
- (void)viewDidUnload
{
_tableView = nil;
[self setTableView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
#end
you forgot to define delegate & datasource for your table, and didn't implement the protocols right as far as i see in your code,
try in your .h file:
#interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
// your implementation...
}
and in your .m file in viewDidLoad
self.tableView.dataSource = self;
self.tableView.delegate = self;
the numberOfRows, cellForRow, etc... methods wont work until you define your delegate & datasource for this table :)

Search in UITableView - NSInvalidArgumentException error

I'm implementing the search bar in a UITableView (tblFriends) with a "SearchBar and search Display controller"
This is my NSarray of dictionaries filteredFriendsList (equal to friendsList NSarray):
{
gender
id
name
picture
}
I have the table view in a UIViewController, (not in a tableViewController) because the table occupies only half view.
This is the code:
INTERFACE:
#import <UIKit/UIKit.h>
#import "ClasseSingleton.h"
#import "FBConnect.h"
#interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
NSArray *friendsList;
NSDictionary *friendsDict;
NSMutableArray *filteredFriendsList;
IBOutlet UITableView *tblFriends;
}
#property (nonatomic, retain) NSArray *friendsList;
#property (nonatomic, retain) NSMutableArray *filteredFriendsList;
-(void)getFriends;
#end
IMPLEMENTATION
#import "ViewController.h"
#implementation ViewController
#synthesize friendsList, filteredFriendsList;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[tblFriends setDelegate:self];
[tblFriends setDataSource:self];
}
- (void)getFriends{
NSLog(#"ENTRATO - getFriends");
//Copy ARRAY in other ARRAY
friendsList = [NSArray arrayWithArray:[ClasseSingleton getFriends]];
filteredFriendsList = [NSArray arrayWithArray:[ClasseSingleton getFriends]];
NSLog(#"getFriends : DESCRIPTION\n\n %#", [friendsList description]);
NSLog(#"Count friendslist: %i", [friendsList count]);
[tblFriends reloadData];
}
// *****TABLE MANAGEMENT***** //
//Nuber of cells
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSLog(#"tabella1");
return [filteredFriendsList count];
}
//Populate the table
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPat{
static NSString * cellIdentifier = #"cell";
//Set Style cell
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
friendsDict = [filteredFriendsList objectAtIndex:indexPat.row];
//Set CELL TEXT
NSString *cellValue = [friendsDict objectForKey:#"name"];
NSLog(#"TBL %#", cellValue);
[cell.textLabel setText:cellValue];
return cell;
}
// SEARCH IN TABLE
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
[self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption{
[self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)saearchBar {
[self.filteredFriendsList removeAllObjects];
[self.filteredFriendsList addObjectsFromArray: friendsList];
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{
/*
Update the filtered array based on the search text and scope.
*/
[self.filteredFriendsList removeAllObjects]; // First clear the filtered array.
/*
Search the main list for products whose type matches the scope (if selected) and whose name matches searchText; add items that match to the filtered array.
*/
NSString *cellTitle;
for (cellTitle in friendsList){
// for (cellTitle in [friendsDict objectForKey:#"name"]){
NSComparisonResult result = [cellTitle compare:searchText options:NSCaseInsensitiveSearch range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame){
[filteredFriendsList addObject:cellTitle];
}
}
}
...
#end
Everytime i put some character in the search bar the app crashes with this error:
'NSInvalidArgumentException', reason: '-[__NSCFDictionary compare:options:range:]: unrecognized selector sent to instance
I hope to solve the problem, it's the 6th days with this error.
Thank you.
You declare filteredFriendsList to be a NSMutableArray, but you're assigning an immuatble NSArray to it here:
filteredFriendsList = [NSArray arrayWithArray:[ClasseSingleton getFriends]];
Change it to this:
filteredFriendsList = [NSMutableArray arrayWithArray:[ClasseSingleton getFriends]];