UITableView push to My webView - objective-c

I'd like to start by apologising as I'm sure this question has been answered, in various forms on this site and others, but I just can't seem to implement any similar threads
It's just I have been trying to push a array of search engines into my webView,
I have populated the table with a .plist or NSMutableArray and I have an array of both kinds with Url's in I have manages to load a subview but I an really struggling to get my web view loading.
I think I'm ok until didSelectRowAtIndexPath and the webView load request. Ok thinking about it I have only populated the table and put IBOUTLET (nonatomic, retain) UIWebView *webView and synthesised it in my WebViewController.
And as Background my TableViewController is embedded in a NavigationController and a WebView in a UIViewController
If anyone is willing to help me out I'm more than willing to donate as this has caused way too many sleepless nights.
Here is a link to my project if it would help anyone http://dl.dropbox.com/u/28335617/TableViewArrays.zip
Thank you very much for any help offered
Here is my TableViewController.h
#class WebViewController;
#import <UIKit/UIKit.h>
#interface TableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate> {
WebViewController *viewController;
IBOutlet UITableView *mytableView;
}
#property (strong, nonatomic) IBOutlet UITableView *mytableView;
#property (nonatomic, retain) WebViewController *viewController;
#property (nonatomic, retain) NSMutableArray *searchData, *tableData, *tableUrl;
#end
Here is my TableViewController.m
#import "TableViewController.h"
#import "TableAppDelegate.h"
#import "WebViewController.h"
#interface TableViewController ()
#end
#implementation TableViewController
#synthesize mytableView;
#synthesize viewController;
#synthesize searchData, tableData, tableUrl;
NSMutableArray *searchData, *tableData, *tableUrl;
- (void)viewDidLoad
{
[super viewDidLoad];
tableUrl = [[NSMutableArray alloc] init];
[tableUrl addObject: #"http://www.google.com"];
[tableUrl addObject: #"http://www.bing.com"];
[tableUrl addObject: #"http://www.dogpile.com"];
[tableUrl addObject: #"http://www.wikipedia.com"];
[tableUrl addObject: #"http://www.ask.com"];
[tableUrl addObject: #"http://www.yahoo.com"];
[tableUrl addObject: #"http://www.aol.com"];
[tableUrl addObject: #"http://www.altavista.com"];
[tableUrl addObject: #"http://www.gigablast.com"];
[tableUrl addObject: #"http://www.msn.com"];
[tableUrl addObject: #"http://www.mamma.com"];
self.title = #"Search Engines";
//ARRAY FOR PLIST
// Find out the path of recipes.plist
NSString *path = [[NSBundle mainBundle] pathForResource:#"searchData" ofType:#"plist"];
searchData = [[NSMutableArray alloc] initWithContentsOfFile:path];
// Load the file content and read the data into arrays
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
tableData = [dict objectForKey:#"SearchEngines"];
// tableUrl = [dict objectForKey:#"SearchAddress"];
// NSString *path = [[NSBundle mainBundle] pathForResource:#"sEArray" ofType:#"plist"];
// sEArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
// NSString *urlArray = [[NSBundle mainBundle] pathForResource:#"urlsArray" ofType:#"plist"];
//urlsArray = [[NSMutableArray alloc] initWithContentsOfFile:urlArray];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (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 [self.tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
}
// Configure the cell...
NSInteger row = [indexPath row];
cell.textLabel.text = [tableData objectAtIndex:row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
#pragma mark - Table view delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
#end
And here is my WebViewController.h
#import <UIKit/UIKit.h>
#interface WebViewController : UIViewController {
NSMutableArray *tableURL;
}
#property (nonatomic, retain) IBOutlet UIWebView *webView;
#property (nonatomic, retain) NSMutableArray *tableUrl;
#end
And WebViewController.m
#import "TableAppDelegate.h"
#import "TableViewController.h"
#import "WebViewController.h"
#interface WebViewController ()
#end
#implementation WebViewController
#synthesize tableUrl;
#synthesize webView;

Not tested. Add SequgeIdentifier "WebView" in IB
in tableviewcontroller add:
- (void)viewDidLoad
{
...
tableUrl = [dict objectForKey:#"SearchAddress"];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self performSegueWithIdentifier:#"WebView" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"WebView"])
{
WebViewController *webViewController = segue.destinationViewController;
NSIndexPath *selectedPath = [self.tableView indexPathForSelectedRow];
webViewController.tableUrl = [tableUrl objectAtIndex:[selectedPath row]];
[self.tableView deselectRowAtIndexPath:selectedPath animated:YES];
}
}
in webviewcontroller
#interface WebViewController : UIViewController {
NSString *tableURL;
}
#property (nonatomic, retain) IBOutlet UIWebView *webView;
#property (nonatomic, retain) NSString *tableUrl;
#end
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//Create a URL object.
NSURL *url = [NSURL URLWithString:tableUrl];
//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webView loadRequest:requestObj];
}

What exactly is not working?
Looking at your code, I immediately see that you cell initiation code is empty
if (cell == nil) {
}
I think you should initiate your cell with something like this:
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

Related

[UICollectionViewCell setItemDictionary:]: unrecognized selector sent to instance

I have a View Controller and in that View Controller, I have a button. On Click that button will slide in a view(ToolOptionsView). In this View I have a Collection View added but I am having this error
[UICollectionViewCell setItemDictionary:]: unrecognized selector sent to instance
The following is my ToolOptionsView.m file-
#import "ToolOptionsView.h"
#interface ToolOptionsView ()
#property(nonatomic, strong) NSMutableArray *toolsList;
#property(nonatomic, strong) NSMutableDictionary *tools;
#end
#implementation ToolOptionsView
-(id)initWithFrame:(CGRect)frame{
self=[super initWithFrame:frame];
if(self){
[self setToolsList];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
self.toolsCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height) collectionViewLayout:flowLayout];
self.toolsCollectionView.delegate = self;
self.toolsCollectionView.dataSource=self;
[self.toolsCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"toolsCell"];
[self addSubview:self.toolsCollectionView];
}
return self;
}
-(void)setToolsList{
self.toolsList =[[NSMutableArray alloc]init];
self.tools =[[NSMutableDictionary alloc]init];
[self.tools setObject:#"Food" forKey:#"title"];
[self.tools setObject:#"food.png" forKey:#"iconImage"];
[self.toolsList addObject:self.tools];
self.tools =[[NSMutableDictionary alloc]init];
[self.tools setObject:#"Drinks" forKey:#"title"];
[self.tools setObject:#"drinks.png" forKey:#"iconImage"];
[self.toolsList addObject:self.tools];
self.tools =[[NSMutableDictionary alloc]init];
[self.tools setObject:#"Near By Restaurants" forKey:#"title"];
[self.tools setObject:#"Restaurants.png" forKey:#"iconImage"];
[self.toolsList addObject:self.tools];
}
#pragma mark-
#pragma mark- UICollectionViewDatasource method
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [self.toolsList count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
MenuItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"toolsCell" forIndexPath:indexPath];
NSMutableDictionary *dict = [self.toolsList objectAtIndex:indexPath.row];
cell.itemDictionary = dict;
return cell;
}
#end
and here is my MenuItemCollectionViewCell.h-
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import <CoreGraphics/CoreGraphics.h>
#interface MenuItemCollectionViewCell : UICollectionViewCell
#property(nonatomic, strong) UIImageView *iconImageView;
#property(nonatomic, strong) UILabel *iconLabel;
#property(nonatomic, strong) NSMutableDictionary *itemDictionary;
#end
and here is my MenuItemCollectionViewCell.m file-
#import "MenuItemCollectionViewCell.h"
#implementation MenuItemCollectionViewCell
-(void)awakeFromNib{
self.iconImageView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20, self.bounds.size.width-40, self.bounds.size.height-40)];
self.iconImageView.image = [UIImage imageNamed:[self.itemDictionary objectForKey:#"iconImage"]];
[self addSubview:self.iconImageView];
self.iconLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 23 + self.iconImageView.bounds.size.height, self.bounds.size.width-10 , 16)];
self.iconLabel.text = [self.itemDictionary objectForKey:#"title"];
[self addSubview:self.iconLabel];
}
#end
In the line
[self.toolsCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"toolsCell"];
you register the class UICollectionViewCell for the identifier but should actually register your custom class MenuItemCollectionViewCell:
[self.toolsCollectionView registerClass:[MenuItemCollectionViewCell class] forCellWithReuseIdentifier:#"toolsCell"];
Most probably the cell returned from dequeResuableCellWithIdentifier Is not a MenuItemCollectionViewCell.
Put a breakpoint after that method and check what tipe of cell is returned in the debugger, just write po cell.class

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")
}
}
}

UITableview - Can't Reload data

I'm noob in Obj-c programming. I'm making an iPad application composed of a ViewController that shows me 2 text boxes , a button in the upper side , just to make a sum.
In the same Viewcontroller, i have a TableView and a Button. This Tableview initially shows me an element, but i'd want to refresh this list just clicking the button.
The function linked at the button to refresh the list ( touch down event ) is called " listaPDF " .
Viewcontroller.h
#import <UIKit/UIKit.h>
#interface VPViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
IBOutlet UITextField *txtPrimoAddendo ;
IBOutlet UITextField *txtSecondoAddendo ;
IBOutlet UILabel *lblTotale ;
IBOutlet UITableView *tabella;
NSMutableArray *lista;
}
#property (nonatomic, retain) IBOutlet UITextField *txtPrimoAddendo;
#property (nonatomic, retain) IBOutlet UITextField *txtSecondoAddendo;
#property (nonatomic, retain) IBOutlet UILabel *lblTotale;
#property (nonatomic, retain) IBOutlet UITableView *tabella;
#property (nonatomic, retain) NSMutableArray *lista;
-(IBAction)somma ;
-(IBAction)listaPDF;
#end
Viewcontroller.m
#import "VPViewController.h"
#interface VPViewController ()
#end
#implementation VPViewController
-(void)somma {
int x = [[txtPrimoAddendo text] intValue];
int y = [[txtSecondoAddendo text] intValue];
int somma = x + y ;
NSString *totale = [NSString stringWithFormat:#"La somma fa : %d", somma];
[lblTotale setText:totale];
[lblTotale setHidden:FALSE];
}
- (void)listaPDF {
int contatore = 1;
NSArray *dirFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[NSBundle mainBundle] resourcePath] error: nil];
for (int i = 0; i < dirFiles.count ; i++) {
NSString *files = dirFiles[i];
int indice = files.length - 4 ;
NSString *extension = [files substringFromIndex:indice];
if([extension isEqual: #".pdf"]) {
NSLog(#"********* File PDF : %#", files);
[lista insertObject:files atIndex:contatore];
contatore++;
}
}
[tabella reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [lista count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"CellID";
UITableViewCell *cell = [tabella dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.imageView.image = [UIImage imageNamed:#"pdf.png"];
cell.textLabel.text = [lista objectAtIndex:indexPath.row];
return cell;
}
- (void)viewDidLoad
{
tabella.delegate = self;
tabella.dataSource = self;
tabella = [[ UITableView alloc] init];
lista = [[NSMutableArray alloc] init];
[lista insertObject:#"FIRST ELEMENT" atIndex:0];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
#synthesize lblTotale;
#synthesize txtPrimoAddendo;
#synthesize txtSecondoAddendo;
#synthesize tabella;
#synthesize lista;
#end
Thanks
I have tried your code as it is.
Why you initializing UITableView object in viewDidLoad. It doesn't need to be allocated if you are adding on Xib file. If you creating UITableView Programmatically then its required. Just comment/remove that initializing line and tableView's delegate methods will be called.
And In 'ListaPDF' function no items is being added to array 'lista', that's why no new entry was visible in UITableView.
NSMutableArray indices begin at 0 - not 1
int contatore = 1;
...
[lista insertObject:files atIndex:contatore];
contatore++;
Use addObject to add an object to a NSMutableArray
[lista addObject:files];
Remove all of your instance variables, because this:
#property (nonatomic, retain) NSMutableArray *lista;
creates an instance variable called _lista - not lista
You have quite a bit of code backwards:
tabella.delegate = self;
tabella.dataSource = self;
tabella = [[ UITableView alloc] init];
lista = [[NSMutableArray alloc] init];
You're trying to set the delegate and datasource before the table is allocated.
It should be:
tabella = [[ UITableView alloc] init];
lista = [[NSMutableArray alloc] init];
tabella.delegate = self;
tabella.dataSource = self;
However the UITableView has been added inside Interface Builder, right?
That means it's already being created for you and you shouldn't be allocating the table here.
Also: inside Interface Builder you can rightclick+drag (or ctrl+leftclick+drag) to connect your UITableView to yourUIViewController as its delegate and datasource

IOS loading a tableview with data

I'm fairly new to iOS and have much more to learn, and hope you guys can guide me from my mistake.
I've recently learned passing data from TableView to DetailView, and thought, why not the other way around. I also start building a StopWatch app, and felt that a log function would be very useful.
With that said, I'm currently building a stopwatch app that works as a timer and have a high score log function. It goes from View(stopwatch) to tableView(log board) I'm using a NSMutableArray as a temp storage to hold the information as they should be lost when the app start/close. Unfortunately, it seem that by following and changing variable here and there, i got myself confuse and stuck now.
Thanks for the suggestion and help you guys gave and thanks #Abizern for giving me tips. Manage to solve all the problem. Shall leave the code here incase anyone in the future do similar things to this.
TimerViewController.h
#import <UIKit/UIKit.h>
#import "SampleData.h"
#import "SampleDataDAO.h"
#import "HighScoreTableViewController.h"
#interface TimerViewController : UIViewController
{
NSTimer *stopWatchTimer; // Store the timer that fires after a certain time
NSDate *startDate; // Stores the date of the click on the start button
}
#property(nonatomic, strong) SampleDataDAO *daoDS;
#property(nonatomic, strong) NSMutableArray *ds;
#property (retain, nonatomic) IBOutlet UILabel *stopWatchLabel;
#property (weak, nonatomic) IBOutlet UIButton *onStartPressed;
#property (weak, nonatomic) IBOutlet UIButton *onStopPressed;
#property (weak, nonatomic) IBOutlet UIButton *onLogPressed;
#property (weak, nonatomic) IBOutlet UIButton *onHighscorePressed;
- (IBAction)onStartPressed:(id)sender;
- (IBAction)onStopPressed:(id)sender;
- (IBAction)onLogPressed:(id)sender;
- (IBAction)onHighscorePressed:(id)sender;
#end
TimerViewController.m
#import "TimerViewController.h"
#interface TimerViewController ()
#end
#implementation TimerViewController
#synthesize stopWatchLabel;
#synthesize onStartPressed;
#synthesize onStopPressed;
#synthesize onLogPressed;
#synthesize onHighscorePressed;
#synthesize ds,daoDS;
- (void)viewDidLoad
{
[super viewDidLoad];
daoDS = [[SampleDataDAO alloc] init];
self.ds = daoDS.PopulateDataSource;
onStopPressed.enabled=false;
}
- (void)viewDidUnload
{
[self setStopWatchLabel:nil];
[self setOnStartPressed:nil];
[self setOnLogPressed:nil];
[self setOnStopPressed:nil];
[self setOnHighscorePressed:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([[segue identifier] isEqualToString:#"showDetail"]) {
HighScoreTableViewController *detailViewController = [segue destinationViewController];
detailViewController.arrayOfSampleData = self.ds;
}
}
- (void)updateTimer
{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss.S"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
stopWatchLabel.text = timeString;
}
- (IBAction)onStartPressed:(id)sender {
startDate = [NSDate date];
// Create the stop watch timer that fires every 10 ms
stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:#selector(updateTimer)
userInfo:nil
repeats:YES];
onStartPressed.enabled=false;
onStopPressed.enabled=true;
}
- (IBAction)onStopPressed:(id)sender {
[stopWatchTimer invalidate];
stopWatchTimer = nil;
[self updateTimer];
onStartPressed.enabled=true;
}
- (IBAction)onLogPressed:(id)sender {
NSString * timeCaptured = stopWatchLabel.text;
static NSInteger i = 1 ;
SampleData* mydata = [[SampleData alloc]init];
mydata.clueName=[NSString stringWithFormat:#"clue %d",i++ ];
mydata.timeLog = timeCaptured;
[self.ds addObject:mydata];
NSLog(#"%#",mydata.clueName);
NSLog(#"time %#", mydata.timeLog);
NSLog(#"%d",[self.ds count]);
mydata=nil;
}
- (IBAction)onHighscorePressed:(id)sender {
NSLog(#"Proceeding to HighScore");
}
#end
HighScoreTableView.h
#import <UIKit/UIKit.h>
#import "SampleData.h"
#import "SampleDataDAO.h"
#import "TimerViewController.h"
#interface HighScoreTableViewController : UITableViewController
#property (nonatomic, strong) NSMutableArray *arrayOfSampleData;
#property (nonatomic, strong) SampleData * highscoreData;
#end
HighScoreTableView.m
#import "HighScoreTableViewController.h"
#interface HighScoreTableViewController ()
#end
#implementation HighScoreTableViewController
#synthesize highscoreData;
#synthesize arrayOfSampleData;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
highscoreData = [[SampleData alloc]init];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.arrayOfSampleData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"highscoreCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//highscoreData = [self.arrayOfSampleData objectAtIndex:indexPath.row];
highscoreData = (SampleData *)[self.arrayOfSampleData objectAtIndex:indexPath.row]; //if above line doesn't work, use this
cell.textLabel.text=[NSString stringWithFormat:#"%# time %#",highscoreData.clueName, highscoreData.timeLog];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
#end
SampleData.h
#import <Foundation/Foundation.h>
#interface SampleData : NSObject
#property(nonatomic,strong) NSString * clueName;
#property(nonatomic,strong) NSString * timeLog;
#end
SampleData.m
#import "SampleData.h"
#implementation SampleData
#synthesize clueName,timeLog;
#end
SampleDataDAO.h
#import <Foundation/Foundation.h>
#import "SampleData.h"
#interface SampleDataDAO : NSObject
#property(nonatomic, strong) NSMutableArray * someDataArray;
-(NSMutableArray *)PopulateDataSource;
#end
SampleDataDAO.m (Not sure if this DAO NSObject is needed)
#import "SampleDataDAO.h"
#implementation SampleDataDAO
#synthesize someDataArray;
-(NSMutableArray *)PopulateDataSource
{
someDataArray = [[NSMutableArray alloc] init];
SampleData * mydata = [[SampleData alloc] init];
mydata = nil;
return someDataArray;
}
#end
There are several missteps in your coding:
You do need to use prepareForSegue to pass data from parent to child view controller. In your case from TimerViewController to HighScoreTableViewController.
In your HighScoreTableViewController class, create an iVar array that will hold the array of sampleData that you will pass over from TimerViewController instant via the prepareForSeque. Something like this:
HighScoreTableViewController.h
#property (nonatomic, strong) NSArray *arrayOfSampleData;
3 . In your prepareForSeque of the TimerViewController, this line is wrong:
//TimerViewController.highscoreData = [self.ds objectAtIndex:[self.tableView indexPathForSelectedRow].row];
Try this:
detailViewController.arrayOfSampleData = self.ds;
4 . In the HighScoreTableViewController.m, under viewDidLoad, replace this
highscoreData = (SampleData *)self.highscoreData;
with:
highscoreData = [SampleData alloc]init];
5 . In numberOfRowsInSection, you now can do this:
return self.arrayOfSampleData.count;
6 . In the cellForRowAtIndexPath,
highscoreData = [self.arrayOfSampleData objectAtIndex:indexPath.row];
//highscoreData = (SampleData *)[self.arrayOfSampleData objectAtIndex:indexPath.row]; //if above line doesn't work, use this
cell.textLabel.text = #"%# time %# ", highscoreData.clueName, highscoreData.timeLog;
In your HighScoreTableViewController you need access to your array e.g. by declaring and defining a writable property:
#property(nonatomic, strong) NSMutableArray *myArr;
then you can define
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.myArr count];
}
and
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// ... like in your code
// Tried changing variable here and there base on tutorial, but can't seem to get it right.**
SampleData * sample = (SampelData *) [self.myArr objectAtIndex:indexPath.row];
cell.textLabel.text = #"%# time %# ",sample.clueName, sample.timeLog;
NSLog(#"Cell Value %d %#",indexPath.row, cell.textLabel.text);
return cell;
}
So basically you just have to change two lines in the definitions of your methods. Most of the time you work with TableViews it is like this: assign the array you want to read data from to a custom property. Return the size of the array in tableView:numberOfRowsInSection: and take an object from the appropiate index to populate a cell in tableView:cellForRowAtIndexPath:.
If the contents of your array changes you have to do extra action to update your table view.
First declare the array in .h file(ex. NSMutableArray *arrStopwatchDetails).
Create the property of that array like #property(nonatomic,retain)NSMutableArray *arrStopwatchDetails.
Synthesize the array in .m file like #synthesize arrStopwatchDetails.
Allocate the array in viewDidLoad or before you want to used.
ex. self.arrStopwatchDetails = [[NSMutableArray alloc]init];
In numberOfRowsInSection method, return the count of array similar to return [self.arrStopwatchDetails count].
In cellForRowsAtIndexPath method, assign value of array element to the cell text as
SampleData * sample = [[[SampleDataDAO alloc]init ].self.arrStopwatchDetails objectAtIndex:indexPath.row];
cell.textLabel.text = #"%# time %# ",sample.clueName, sample.timeLog;
Thats it.

iOS UITableView Only Reloads Cell Data When Scrolling

I am working on my first Objective-C app for iOS and am having an issue with reloading the data in a UITableView.
After reloading the data the cell content will only update when the cell is scrolled above of below the viewable area of the container.
Here is my .h code:
#import <UIKit/UIKit.h>
#import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h"
#interface HelloWorldViewController : UIViewController <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>{
NSMutableArray *tableViewArray;
IBOutlet UITableView *tableView;
}
#property (nonatomic, retain) NSMutableArray *tableViewArray;
#property (weak, nonatomic) IBOutlet UILabel *connectionLabel;
#property (nonatomic, retain) IBOutlet UITableView *tableView;
#property (weak, nonatomic) IBOutlet UITextView *textArea;
#property (weak, nonatomic) IBOutlet UITextField *textField2;
#property (weak, nonatomic) IBOutlet UILabel *label;
#property (weak, nonatomic) IBOutlet UITextField *textField;
#property (copy, nonatomic) NSString *userName;
#property (copy, nonatomic) NSString *passWord;
#property (copy, nonatomic) NSMutableString *serverResponse;
- (IBAction)callHome:(id)sender;
#end
and .m code:
#import "HelloWorldViewController.h"
#interface HelloWorldViewController ()
#end
#implementation HelloWorldViewController
#synthesize tableViewArray;
#synthesize connectionLabel;
#synthesize userName = _userName;
#synthesize passWord = _password;
#synthesize serverResponse = _serverResponse;
#synthesize tableView;
#synthesize textArea;
#synthesize textField2;
#synthesize label;
#synthesize textField;
- (void)viewDidLoad
{
[super viewDidLoad];
tableViewArray = [[NSMutableArray alloc] init];
[tableViewArray addObject:#"TEST1"];
[tableViewArray addObject:#"TEST2"];
[tableViewArray addObject:#"TEST3"];
}
- (void)viewDidUnload
{
[self setTextField:nil];
[self setLabel:nil];
[self setTextField2:nil];
[self setTextArea:nil];
[self setTableView:nil];
[self setConnectionLabel:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
if (theTextField == self.textField) {
[theTextField resignFirstResponder];
}
return YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableViewArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.text = [self.tableViewArray objectAtIndex: [indexPath row]];
return cell;
}
- (IBAction)callHome:(id)sender {
self.userName = self.textField.text;
self.passWord = self.textField2.text;
NSMutableString *tempResponse = [[NSMutableString alloc] initWithFormat:#""];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://example.com/"]];
[client setAuthorizationHeaderWithUsername:self.userName password:self.passWord];
[client getPath:#"login.do" parameters:nil
success:^( AFHTTPRequestOperation *operation , id responseObject ){
NSLog(#"Authentication Success: %d", operation.response.statusCode);
self.serverResponse = [NSMutableString stringWithFormat:#"Authentication Success: %d", operation.response.statusCode ];
[tempResponse appendString: self.serverResponse];
self.textArea.text = tempResponse;
}
failure:^(AFHTTPRequestOperation *operation , NSError *error){
NSLog(#"Authentication Error: %#\n%#", error, operation);
}
];
[client getPath:#"test.json.do" parameters:nil
success:^( AFHTTPRequestOperation *operation , id responseObject ){
NSLog(#"Retrieval Success: %d", operation.response.statusCode);
NSDictionary *results = [operation.responseString JSONValue];
NSMutableArray *buildings = [results objectForKey:#"buildings"];
NSMutableArray *names = [[NSMutableArray alloc] init];
for (NSDictionary *building in buildings)
{
[names addObject:[building objectForKey:#"name"]];
}
self.tableViewArray = names;
self.serverResponse = [NSMutableString stringWithFormat:#"\nBuilding List Retrieval Success: %d", operation.response.statusCode ];
[tempResponse appendString: self.serverResponse];
self.connectionLabel.text = tempResponse;
}
failure:^(AFHTTPRequestOperation *operation , NSError *error){
NSLog(#"Retrieval Error: %#\n%#", error, operation);
}
];
NSLog(#"tableView is: %#", [tableView description]);
[tableView reloadData];
}
#end
When I call [self.tableView description]the result is null, but if I call it from cellForRowAtIndexPath then I get the following result:
tableView is: <UITableView: 0x8a71000; frame = (0 0; 280 191); clipsToBounds = YES; autoresize = W+H; layer = <CALayer: 0x6b7e860>; contentOffset: {0, 0}>. Delegate: HelloWorldViewController, DataSource: HelloWorldViewController
Here's a screenshot of interface builder:
All help is appreciated! Thanks!
You're probably not connecting the UITableView in the interface builder..
You have to drag while pressing ctrl from the file's owner to the UITableView and connect it.
Also, you should not access your properties without self, you should do:
#synthesize tableViewArray = _tableViewArray;
and then access it with:
self.tableViewArray
try to avoid accessing your ivars directly, use the property!
Good luck!
It looks like you may have not hooked up your UITableView with the HelloWorldViewController tabelView property in IB.