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.
Related
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
I'm just trying to understand how delegate works and I'm in troubles.
I have two classes (both UIViewController) connected into the storyboard, the first one (ViewController.h/m) hold a TableView with cells and the second one (AddNameViewController.h/m) simply hold a TextField (where I want to write) and a button (Add Name)
as you surely understand I want the button pressed to send to the TableView what is written into the TextField, pretty simple.
And since I have two different Controllers and an Array containing the data holds by the tableview, I want to connect them with a delegate (just to learn it).
here is some code:
ViewController.h
#import "AddNameViewController.h"
#interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, AddNameViewControllerDelegate>
#property (strong, nonatomic) NSMutableArray *array;
#end
ViewController.m
#import "ViewController.h"
#import "AddNameViewController.h"
#inferface ViewController ()
#end
#implementation ViewController
#synthesize array;
-(void)addStringWithString:(NSString*)string
{
[self.array addObject:string];
NSLog(#"%#", array);
}
-(void)viewDidLoad
{
AddNameViewController *anvc = [[AddNameViewController alloc] init];
anvc.delegate = self;
array = [[NSMutableArray alloc] initWithObjects:#"first", #"second", nil];
NSLog(#"%#", array);
[super viewDidLoad];
}
-(NSInteger)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSindexPath*)indexPath
{
static NSString *simpleTableIdentifier = #"RecipeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
}
#end
AddNameViewController.h
#protocol AddNameViewControllerDelegate <NSObject>
-(void)addStringWithString:(NSString*)string;
#end
#interface AddNameViewController : UIViewController
#property (weak, nonatomic) id <AddNameViewControllerDelegate> delegate;
#property (weak, nonatomic) IBOutlet UITextField *myTextField;
-(IBAction)add:(id)sender;
#end
finally the AddNameViewController.m
#import "ViewController.h"
#interface AddNameViewController ()
#end
#implementation AddNameViewController
#synthesize myTextField, delegate;
-(id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
-(void)viewDidLoad
{
[super viewDidLoad];
}
-(IBAction)add:(id)sender
{
[self.delegate addStringWithString:self.myTextField.text];
// I've also tried with this but nothing --> [self.delegate addStringWithString:#"aa"];
}
#end
The array is initialized properly, no errors, no warnings, no crashes, simply seems like the method "addStringWithString" is not even called, because is not even NSLog anything.
obviously everything in connected in the storyboard, methods and outlets, thanks for your help.
in interface builder of AddNameViewController, did you connect the button event (Touch Up inside) into the action -(IBAction)add:(id)sender ?
also try this
-(IBAction)add:(id)sender
{
if([self.delegate respondsToSelector:#selector(addStringWithString:)]) {
[self.delegate addStringWithString:self.myTextField.text];
}
// I've also tried with this but nothing --> [self.delegate addStringWithString:#"aa"];
}
I'm trying to implement saving of user preferences in my OS X app. I have an NSTableView which stores its data to my .plist file, but I have troubles loading same data back to my NSTableView.
My model object:
#import <Foundation/Foundation.h>
#interface UserKeys : NSObject <NSCoding>
#property (nonatomic, copy) NSString *userKeyName;
#property (nonatomic, copy) NSString *userApi;
#property (nonatomic, copy) NSString *userCode;
#end
and its implementation:
#import "UserKeys.h"
#implementation UserKeys
- (id)init
{
self = [super init];
if (self) {
//
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
self.userKeyName = [aDecoder decodeObjectForKey:#"userKeyName"];
self.userApi = [aDecoder decodeObjectForKey:#"userApi"];
self.userCode = [aDecoder decodeObjectForKey:#"userCode"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)enCoder {
[enCoder encodeObject:self.userKeyName forKey:#"userKeyName"];
[enCoder encodeObject:self.userApi forKey:#"userApi"];
[enCoder encodeObject:self.userCode forKey:#"userCode"];
}
#end
My preferences view controller header:
#import <Cocoa/Cocoa.h>
#import "MASPreferencesViewController.h"
#import "UserKeys.h"
#interface PreferencesApiKeysViewController : NSViewController <MASPreferencesViewController>
#property (strong) NSMutableArray *allKeys;
#end
and its implementation:
#import "PreferencesApiKeysViewController.h"
#import "UserKeys.h"
#interface PreferencesApiKeysViewController ()
#property (weak) IBOutlet NSTableView *keysTableView;
#end
#implementation PreferencesApiKeysViewController
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle {
if ((self = [super initWithNibName:nibName bundle:bundle])) {
self.allKeys = [NSMutableArray array];
}
return self;
}
// delegating....
//
- (void)viewWillAppear {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:#"UserKeys"];
if (data != nil) {
NSArray *oldArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if (oldArray != nil) {
self.allKeys = [[NSMutableArray alloc] initWithArray:oldArray];
} else {
self.allKeys = [NSMutableArray array];
}
}
}
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
// some code...
return cellView;
}
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
return [self.allKeys count];
}
The error I'm getting is:
-[UserKeys count]: unrecognized selector sent to instance 0x100534df0
When I put a breakpoint in - (void)viewWillAppear, I can see that data has around 250 bytes, but this oldArray seems to be empty. I understand that I'm doing some major mistake here with self.allKeys so that my table is not aware how many rows it should create, but after lots of attempts to get proper data, I'm really out of ideas why is this happening.
So, how to properly unarchive my data and present it in NSTableView?
(I'm using Xcode 4.6)
It is because the object you appear to be dearchiving is a pointer to an object of class UserKeys, rather than an object that is or descends from NSArray. When -initWithAray: hits your oldArray pointer to UserKeys, it doesn't know, or doesn't care what class it is, it simply sends it a -count message so as to ascertain the size it must grow to.
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];
I'm trying to save the name of a button using a singleton so that the name can be accessed in another view to play a video with the same name. However, I'm getting the error: SIGABRT. I don't really see what's wrong with my code. Any ideas?
#import "List.h"
#import "MyManager.h"
#import "Video.h"
#implementation ExerciseList
-(IBAction) goToVideo:(UIButton *) sender{
MyManager *sharedManager = [MyManager sharedManager];
sharedManager.vidName = [[sender titleLabel] text];
Video *videoGo = [[Video alloc] initWithNibName: #"Video" bundle: nil];
[self.navigationController pushViewController: videoGo animated: YES];
[videoGo release];
}
Here is my .h and .m for MyManager:
#import <foundation/Foundation.h>
#interface MyManager : NSObject {
NSMutableArray *workouts;
NSString *vidName;
}
#property (nonatomic, retain) NSMutableArray *workouts;
#property (nonatomic, retain) NSString *vidName;
+ (id)sharedManager;
#end
#import "MyManager.h"
static MyManager *sharedMyManager = nil;
#implementation MyManager
#synthesize workouts;
#synthesize vidName;
#pragma mark Singleton Methods
+ (id)sharedManager {
#synchronized(self) {
if (sharedMyManager == nil)
sharedMyManager = [[self alloc] init];
}
return sharedMyManager;
}
- (id)init {
if ((self = [super init])) {
workouts = [[NSMutableArray alloc] init];
vidName = [[NSString alloc] init];
}
return self;
}
-(void) dealloc{
self.workouts = nil;
self.vidName = nil;
[super dealloc];
}
#end
You should access the title of the button
sharedManger.vidName = [sender currentTitle];
However you are not using ARC so also check where your vidName property is retain or copy.
if it is not retain or copy then you can use this code also
if(sharedManger.vidname != nil){
[sharedManger.vidName release];
sharedManger.vidName = nil;
}
sharedManger.vidName = [[sender currentTitle] retain];