I have a UITableview that I have populated with data from a database, I know what to send data to another view (the detailViewController), however I can't get it to work, right now I am sending data via the - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { method. I have two classes the UITableview class and the detail class they are below. I also have an NSObject class that holds the objects for the database. Please check it out, here's my code:
UITableView Class code.:
Header File
#import <UIKit/UIKit.h>
#import <sqlite3.h>
#interface ExerciseViewController : UITableViewController {
NSMutableArray *theauthors;
sqlite3 * db;
}
#property(nonatomic,retain) NSMutableArray *theauthors;
-(NSMutableArray *) authorList;
#end
Implementation File
#import "ExerciseViewController.h"
#import "sqlColumns.h"
#import <sqlite3.h>
#import "UIColor+FlatUI.h"
#import "ExerciseDetailViewController.h"
#interface ExerciseViewController ()
#end
#implementation ExerciseViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Abdominal";
[self authorList];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.theauthors count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"exerciseCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
sqlColumns *author = [self.theauthors objectAtIndex:indexPath.row];
UILabel *exerciseName = (UILabel *)[cell viewWithTag:101];
exerciseName.text = author.Name;
UILabel *equipment = (UILabel *)[cell viewWithTag:102];
equipment.text = author.Equipment;
NSString *string = author.Equipment;
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
if ([trimmedString isEqualToString:#"null"]) {
equipment.text = #"No Equipment";
}
UILabel *difficulty = (UILabel *)[cell viewWithTag:103];
difficulty.text = author.Difficulty;
if ([difficulty.text isEqualToString:#"Easy"]) {
difficulty.textColor = [UIColor emerlandColor];
}
if ([difficulty.text isEqualToString:#"Intermediate"]) {
difficulty.textColor = [UIColor belizeHoleColor];
}
if ([difficulty.text isEqualToString:#"Hard"]) {
difficulty.textColor = [UIColor alizarinColor];
}
if ([difficulty.text isEqualToString:#"Very Hard"]) {
difficulty.textColor = [UIColor alizarinColor];
}
UIImageView *cellImageView = (UIImageView *)[cell viewWithTag:100];
cellImageView.image = [UIImage imageNamed:[NSString stringWithFormat:#"%#",author.File]];
UIView *bgColorView = [[UIView alloc] init];
bgColorView.backgroundColor = [UIColor cloudsColor];
bgColorView.layer.masksToBounds = YES;
[cell setSelectedBackgroundView:bgColorView];
return cell;
}
-(NSMutableArray *) authorList{
_theauthors = [[NSMutableArray alloc] initWithCapacity:10];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"StayhealthyExercises.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured: %s", sqlite3_errmsg(db));
}
const char *query = "SELECT * FROM strengthexercises WHERE primarymuscle LIKE '%abdominal%'";
const char *sql = query;
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}else{
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
sqlColumns * author = [[sqlColumns alloc] init];
author.Name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
author.Muscle = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
author.Description = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 3)];
author.File= [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 4)];
author.Sets= [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 5)];
author.Reps= [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 6)];
author.Equipment= [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 7)];
author.PrimaryMuscle= [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 8)];
author.SecondaryMuscle= [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 9)];
author.Difficulty= [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 10)];
[_theauthors addObject:author];
}
}
sqlite3_finalize(sqlStatement);
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}
#finally {
sqlite3_close(db);
return _theauthors;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"detail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
sqlColumns *author = [self.theauthors objectAtIndex:indexPath.row];
ExerciseDetailViewController *destViewController = segue.destinationViewController;
destViewController.exerciseImage.image = [UIImage imageNamed:author.File];
destViewController.descriptionLabel.text = author.Description;
}
}
#end
Now the DetailViewController
Header file:
#import <UIKit/UIKit.h>
#import "sqlColumns.h"
#interface ExerciseDetailViewController : UIViewController
#property (weak, nonatomic) IBOutlet UIImageView *exerciseImage;
#property (weak, nonatomic) IBOutlet UILabel *descriptionLabel;
#property (nonatomic, strong) sqlColumns *author;
#end
Implementation File
#import "ExerciseDetailViewController.h"
#import "ExerciseViewController.h"
#interface ExerciseDetailViewController ()
#end
#implementation ExerciseDetailViewController
#synthesize exerciseImage,descriptionLabel,author;
- (void)viewDidLoad
{
[super viewDidLoad];
descriptionLabel.text = author.Description;
NSLog(#"%#",author.Description);
}
#end
Must be a small error, any help would be greatly appreciated!
I think the problem is that your outlets are nil. You can only set the text and the image after the viewDidLoad get called.
Try to save your info in other properties and after viewDidLoad get called assign this info to your label and image view.
In your prepare for segue:
destViewController.image = [UIImage imageNamed:author.File];
destViewController.text = author.Description;
In your header add those properties:
#property (strong, nonatomic) UIImage *image;
#property (strong, nonatomic) NSString *text;
Then in your viewDidLoad:
exerciseImage.image = self.image;
descriptionLabel.text = self.text;
Related
In my class for my TableView, I populate the rows with the names of all files within a given folder of my app. I am just now changing it over to UISearchBar, and I'm having some issues with my logic. The search bar appears, but the tableview simply goes blank.
In my .h file I have:
#interface DevoSongs : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchResultsUpdating >{
NSArray *files;
NSIndexPath *thepath;
NSString *filenames;
NSArray *try2;
NSMutableArray *searchResults;
NSString *savedSearchTerm;
IBOutlet UITableView *tableView;
}
#property (nonatomic, retain) UITableView *tableView;
#property (strong, nonatomic) UISearchController *searchController;
#property (nonatomic, retain) NSArray *files;
#property (nonatomic, retain) NSString *filenames;
#property (nonatomic, retain) NSIndexPath *thepath;
#property (nonatomic, retain) NSArray *try2;
#property (nonatomic, retain) NSMutableArray *searchResults;
#property (nonatomic, copy) NSString *savedSearchTerm;
- (void)handleSearchForTerm:(NSString *)searchTerm;
#end
For my implementation:
-(void)viewDidLoad {
[super viewDidLoad];
self.searchController = [[UISearchController alloc]
initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.searchBar.delegate = self;
self.tableView.tableHeaderView = self.searchController.searchBar;
self.definesPresentationContext = YES;
[self.searchController.searchBar sizeToFit];
}
- (void)viewWillAppear:(BOOL)animated {
NSBundle *bundle = [NSBundle mainBundle];
self.files = [bundle pathsForResourcesOfType:#"pdf" inDirectory:#"thepdfpowerpoints"];
NSString *documentsDirectoryPath = [self.files objectAtIndex:thepath.row];
self.title = #"Devo Songs";
self.filenames = [[documentsDirectoryPath lastPathComponent] stringByDeletingPathExtension];
NSMutableArray *names = [NSMutableArray arrayWithCapacity:[self.files count]];
for (NSString *path in self.files) {
[names addObject:[[path lastPathComponent] stringByDeletingPathExtension]];
}
self.files = [names sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.tableView.backgroundColor = [UIColor darkGrayColor];
self.view.backgroundColor = [UIColor grayColor];
[super viewWillAppear:animated];
}
- (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.
if (self.searchController.isActive) {
return [searchResults count];
}
else {
return [self.files count];
}
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *filename = [[[self.files objectAtIndex:indexPath.row] lastPathComponent] stringByDeletingPathExtension];
NSInteger row = [indexPath row];
NSString *contentForThisRow = nil;
contentForThisRow = filename;
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ) {
[[cell textLabel] setText:contentForThisRow];
cell.textLabel.font = [UIFont fontWithName:#"Roboto-Bold" size:38];
cell.textLabel.textColor = [UIColor whiteColor];
cell.backgroundColor = [UIColor blackColor];
return cell;
}
else {
[[cell textLabel] setText:contentForThisRow];
cell.textLabel.font = [UIFont fontWithName:#"Roboto-Bold" size:22];
cell.textLabel.textColor = [UIColor whiteColor];
cell.backgroundColor = [UIColor darkGrayColor];
return cell;
}
}
- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope{
[self updateSearchResultsForSearchController:self.searchController];
}
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
NSString *searchString = self.searchController.searchBar.text;
NSPredicate *resultPredicate;
resultPredicate = [NSPredicate predicateWithFormat:#"SELF contains[c] %#",searchString];
searchResults = [self.files filteredArrayUsingPredicate:resultPredicate];
NSLog(#"results %lu", (unsigned long)[self.files count]);
[self.tableView reloadData];
}
Remove below code or comment below
- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope{
[self updateSearchResultsForSearchController:self.searchController];}
Added the another searchController delegate method in your called show below.
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange (NSRange)range replacementText:(NSString *)text {
[self updateSearchResultsForSearchController:self.searchController];}
This should work. Hope it help :)
I am Working on a Program which looks like this:
There is a Table View i that there is a Custom Table View Cell.
And there is a UISlider , Label and Button on Custom View Cell
Now the Problem is when i slide the UISlider of Cell : 0 than the UISlider at Cell : 12(or later Cell) is Automatically assigned the Cell:0's UISlider Value(Thanks To ARC..!!).
Now anyone have a solution so that the later cell's UISlider doest change while i change value of upper Cells.
P.S. When i assigned a UiSlider Value at Cell:0 and Scroll Up and Down it is automatically random Cell's UISlider Value is changing.
Google Drive Link of Project :
Slider Program
I am Using xCode 5 and iOS SDK 7.
Thanks for Reading.
Edit:
cellForRowAtIndexPath Method
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableCell = #"Cell";
CustomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableCell];
if (cell == nil) {
cell = [[CustomeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableCell];
}
NSString *strName = [NSString stringWithFormat:#"Cell : %d",indexPath.row];
// NSLog(#"strName :%# , SliderValue : %d",strName , (int)cell.mySlider.value);
for (int i = 0; i < arrSlider.count; i++) {
NSString *strTag = [NSString stringWithFormat:#"%#",[[arrSlider objectAtIndex:i]valueForKey:#"tag"]];
NSString *myIndexPath = [NSString stringWithFormat:#"%d",indexPath.row];
if([strTag isEqualToString:myIndexPath])
{
NSString *strValue = [NSString stringWithFormat:#"%#",[[arrSlider objectAtIndex:i]valueForKey:#"value"]];
cell.mySlider.value = [strValue floatValue];
NSLog(#"Tag Value : %# , value %f", strTag , [strValue floatValue]);
}
}
[cell.btnCell setTitle:strName forState:UIControlStateNormal];
cell.btnCell.tag = indexPath.row;
cell.mySlider.tag = indexPath.row;
[cell.mySlider addTarget:self action:#selector(customSliderValue:) forControlEvents:UIControlEventValueChanged];
[cell.btnCell addTarget:self action:#selector(customeBtnClicked:) forControlEvents:UIControlEventTouchDown];
return cell;
}
Use NSMutableDictionary to hold the values of slider then update it from the cellForRowAtIndexPath method i am posting the changes just make changes in your project
in ViewCOntroller.h file
#import <UIKit/UIKit.h>
#import "CustomeTableViewCell.h"
#interface ViewController : UIViewController <UITableViewDataSource ,UITableViewDelegate,SliderDelegate>//confirms to delegate
{
//NSArray *tableList;
UITableView *mytableview;
NSInteger SliderChangeValue;
}
#property (strong , nonatomic) IBOutlet UIView *tableDemo;
#property (strong , nonatomic) NSMutableArray *arrSlider;
#property (strong, nonatomic) NSMutableDictionary *sliderDicValues; //add a mutable dictionary
#property (weak, nonatomic) IBOutlet UITableView *myTableView;//add outlet to tableview
#end
in ViewController.mfile
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize arrSlider;
#synthesize sliderDicValues;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// tableList = [NSArray arrayWithObjects:
// #"Cell 1",#"Cell 2",#"Cell 3",#"Cell 4",#"Cell 5",
// #"Cell 6",#"Cell 7",#"Cell 8",#"Cell 9",#"Cell 10",
// #"Cell 11",#"Cell 12",#"Cell 13",#"Cell 14",#"Cell 15",
// #"Cell 16",#"Cell 17",#"Cell 18",#"Cell 19",#"Cell 20",
// nil];
arrSlider = [[NSMutableArray alloc]init];
sliderDicValues = [[NSMutableDictionary alloc]init]; //initilise an mutable dictionary
//[mytableview registerClass:[CustomeTableViewCell class] forCellReuseIdentifier:#"Cell"];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//[tableList count]
return 15;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableCell = #"Cell";
CustomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableCell];
if (cell == nil) {
cell = [[CustomeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableCell];
}
if([self.sliderDicValues objectForKey:[NSString stringWithFormat:#"%d",indexPath.row]]) //check if there is any slided value is present
{
NSNumber *value = [self.sliderDicValues objectForKey:[NSString stringWithFormat:#"%d",indexPath.row]];
[cell.mySlider setValue:value.integerValue]; //set the slider value
[cell.myCellLabel setText:[NSString stringWithFormat:#"%d",value.integerValue]];//and also label
}
else //set to default values
{
[cell.mySlider setValue:(NSInteger)0];
[cell.myCellLabel setText:#"label"];
}
//add a single target don't add double target to slider
cell.sliderDelegate = self;//set the delegate
return cell;
/*
NSString *strName = [NSString stringWithFormat:#"Cell : %d",indexPath.row];
NSLog(#"strName :%# , SliderValue : %d",strName , (int)cell.mySlider.value);
for (int i = 0; i < arrSlider.count; i++) {
NSString *strTag = [NSString stringWithFormat:#"%#",[[arrSlider objectAtIndex:i]valueForKey:#"tag"]];
NSString *myIndexPath = [NSString stringWithFormat:#"%d",indexPath.row];
if([strTag isEqualToString:myIndexPath])
{
NSString *strValue = [NSString stringWithFormat:#"%#",[[arrSlider objectAtIndex:i]valueForKey:#"value"]];
cell.mySlider.value = [strValue floatValue];
NSLog(#"Tag Value : %# , value %f", strTag , [strValue floatValue]);
}
if ([strTag isEqual:myIndexPath]) {
//NSString *strValue = [NSString stringWithFormat:#"%#",[[arrSlider objectAtIndex:i]objectForKey:#"value"]];
//NSLog(#"%#",strValue);
NSLog(#"Hello");
//cell.mySlider.value =
}
}
[cell.btnCell setTitle:strName forState:UIControlStateNormal];
cell.btnCell.tag = indexPath.row;
cell.mySlider.tag = indexPath.row;
[cell.mySlider addTarget:self action:#selector(customSliderValue:) forControlEvents:UIControlEventValueChanged];
[cell.btnCell addTarget:self action:#selector(customeBtnClicked:) forControlEvents:UIControlEventTouchDown];
*/
}
//delegate method called from custom cell
- (void)sliderChanged:(CustomeTableViewCell *)cell
{
NSIndexPath *path = [_myTableView indexPathForCell:cell]; //get the indexpath
if(path)//check if valid path
{
SliderChangeValue = cell.mySlider.value;
[self.sliderDicValues setObject:[NSNumber numberWithInt:SliderChangeValue] forKey:[NSString stringWithFormat:#"%d",path.row]]; //set the value in the dictionary later used in the cellForRowAtIndexPath method
}
// SliderChangeValue = (int)sender.value;
NSLog(#"%d",SliderChangeValue);
}
//dont use it
-(void)customSliderValue:(UISlider *)sender{
// NSString *value =[NSString stringWithFormat:#"%d" ,(int)sender.value];
// NSString *tag = [NSString stringWithFormat:#"%d", (int)sender.tag];
//
// NSLog(#"%# %#",value , tag);
//
// [self.dicSilder setObject:value forKey:#"value"];
// [self.dicSilder setObject:tag forKey:#"tag"];
//
// [self.arrSlider addObject:self.dicSilder];
// NSLog(#"%#",self.arrSlider);
SliderChangeValue = (int)sender.value;
NSLog(#"%d",SliderChangeValue);
}
//this is also put a delegate from the cell like slider , just add the another method in the protocol and perform action, if u don't get just comment i will update the code and u hav t modify this method according to your requirement
-(void)customeBtnClicked:(UIButton *)sender
{
NSString *value =[NSString stringWithFormat:#"%d" ,SliderChangeValue];
NSString *tag = [NSString stringWithFormat:#"%d", sender.tag];
//NSLog(#"%# %#",value,tag);
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
[dic setObject:value forKey:#"value"];
[dic setObject:tag forKey:#"tag"];
//NSLog(#"%#",dic);
[arrSlider addObject:dic];
NSLog(#"%#",arrSlider);
NSString *sliderTagAtIndexPath = #"";
//NSString *sliderValueAtindexPath = #"";
for (int i = 0; i < arrSlider.count; i++) {
NSString *strTag = [NSString stringWithFormat:#"%#",[[arrSlider objectAtIndex:i]valueForKey:#"tag"]];
if([strTag isEqualToString:tag])
{
//NSString *strValue = [NSString stringWithFormat:#"%#",[[arrSlider objectAtIndex:i]valueForKey:#"value"]];
sliderTagAtIndexPath = strTag;
//sliderValueAtindexPath = strValue;
}
}
UIAlertView *myAlertView = [[UIAlertView alloc]initWithTitle:#"Clicked"
message:[NSString stringWithFormat:#"Cell : %# Value: %d", sliderTagAtIndexPath ,SliderChangeValue]
//message:[NSString stringWithFormat:#"Cell : %# Value: %#", sliderTagAtIndexPath ,sliderValueAtindexPath]
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[myAlertView show];
}
#end
in CustomeTableViewCell.h file
#import <UIKit/UIKit.h>
//add a custom delegate
#protocol SliderDelegate<NSObject>
- (void)sliderChanged:(id)self;
#end
#interface CustomeTableViewCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *myCellLabel;
#property (weak, nonatomic) IBOutlet UISlider *mySlider;
#property (weak, nonatomic) IBOutlet UIButton *btnCell;
#property (weak, nonatomic) id <SliderDelegate>sliderDelegate;
- (IBAction)sliderValuechanged:(UISlider *)sender;
#end
in CustomeTableViewCell.m file
#import "CustomeTableViewCell.h"
#implementation CustomeTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)awakeFromNib
{
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (IBAction)sliderValuechanged:(UISlider *)sender
{
self.myCellLabel.text = [NSString stringWithFormat:#"%d",(NSInteger)sender.value];
//call the custom delegate each time when slider is slided
if([_sliderDelegate respondsToSelector:#selector(sliderChanged:)])
{
[_sliderDelegate sliderChanged:self]; //passing the entire cell itself
}
}
#end
Hope this helps u .. :)
You don't need to check(set) all the datasource for a Cell , I mean, No need of for loop inside the cellForRowAtIndexPath. just remove it and will work fine .
Try this code it works for me :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = [NSString stringWithFormat:#"%d",indexPath.row];
CustomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[CustomeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
// Write your rest code here
return cell;
}
I'm trying to implement the searchBar following steps in this Video
But I got the following exception when I press the searchBar
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do regex matching on object <Authors: 0x10960c1e0>.'
AuthorsTableViewController.h
#interface AuthorsTableViewController : UITableViewController <UISearchBarDelegate> {
NSMutableArray *authorsArray;
NSMutableArray *resultArray;
QuotesNavController *quotes;
}
#property (nonatomic, strong) IBOutlet UISearchBar *SearchBar;
#property (nonatomic, retain) NSMutableArray *authorsArray;
#property (nonatomic, retain) NSMutableArray *resultArray;
-(sqlite3 *) openDataBase;
-(IBAction)backToQuotes:(id)sender;
#end
AuthorsTableViewController.m
#import "AuthorsTableViewController.h"
#interface AuthorsTableViewController ()
#end
#implementation AuthorsTableViewController
#synthesize authorsArray, resultArray;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self retrieveDataFromSqlite];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(IBAction)backToQuotes:(id)sender{
[self performSegueWithIdentifier:#"backToQuotes" sender:sender];
}
-(sqlite3 *) openDataBase{
sqlite3 *database;
NSString *sqLiteDb = [[NSBundle mainBundle] pathForResource:#"SuccessQuotes" ofType:#"sqlite"];
if (sqlite3_open([sqLiteDb UTF8String], &database) != SQLITE_OK) {
NSLog(#"Failed to open database!");
}else{
NSLog(#"database opened!");
}
return database;
}
-(void) retrieveDataFromSqlite{
authorsArray = [[NSMutableArray alloc] init];
sqlite3 *myDatabase = [self openDataBase];
const char *sqlSelect = "SELECT *, COUNT(qu_author) AS count FROM authors JOIN quotes ON _auid = qu_author GROUP BY au_name ORDER BY au_name ASC";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(myDatabase, sqlSelect, -1, &compiledStatement, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
int author_id = sqlite3_column_int(compiledStatement, 0);
NSString *au_name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 1)];
NSString *au_picture = [NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 2)];
int quotes_id = sqlite3_column_int(compiledStatement, 3);
NSString *quotes_content = [NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 4)];
int quotes_author = sqlite3_column_int(compiledStatement, 5);
NSString *quotes_favorite = [NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 6)];
int count = sqlite3_column_int(compiledStatement, 7);
Authors *authors = [[Authors alloc] initWithUniqueId:author_id au_name:au_name au_picture:au_picture quotes_id:quotes_id quotes_content:quotes_content quotes_author:quotes_author quotes_author:quotes_author quotes_favorite:quotes_favorite count:count];
[authorsArray addObject:authors];
} // while end
}// prepare end
sqlite3_finalize(compiledStatement);
sqlite3_close(myDatabase);
}
- (void) searchThroughtData {
self.resultArray = nil;
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF like[c] %#",[NSString stringWithFormat:#"%#*",self.SearchBar.text]];
self.resultArray = [[self.authorsArray filteredArrayUsingPredicate:resultPredicate] mutableCopy];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.tableView) {
return [authorsArray count];
} else {
[self searchThroughtData];
return [resultArray count];
}
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[self searchThroughtData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"authorCell";
AuthorsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[AuthorsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
Authors *temp_items;
if (tableView == self.tableView) {
temp_items = [self.authorsArray objectAtIndex:indexPath.row];
}else{
temp_items = [self.resultArray objectAtIndex:indexPath.row];
}
[cell.authorName setText:[NSString stringWithFormat:#"%#",temp_items.au_name]];
[cell.count setTitle:[NSString stringWithFormat:#"%d",temp_items.count] forState:UIControlStateNormal];
UIImage *theImage = [UIImage imageNamed:temp_items.au_picture];
cell.authorPic.image = theImage;
UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:93/255.0
green:45/255.0
blue:22/255.0
alpha:0.5];
cell.selectedBackgroundView = customColorView;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
Authors *temp_items = [self.authorsArray objectAtIndex:indexPath.row];
quotes = [self.storyboard instantiateViewControllerWithIdentifier:#"QuotesNavController"];
quotes.quType = 3;
quotes.authorId = temp_items.author_id;
[self presentModalViewController:quotes animated:YES];
}
#end
This is my View Controller, as you can see, there is a UITableView in the lower part.
I put the delegate and datasource in the .h file
#interface CourseFindrViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
While my .m file is this:
#interface CourseFindrViewController ()
{ sqlite3 *_db;}
#property (nonatomic, weak) IBOutlet UILabel *jNameLabel;
#property (weak, nonatomic) IBOutlet UITextView *jDescLabel;
#property (nonatomic, weak) IBOutlet UILabel *jEarningsLabel;
#property (weak, nonatomic) IBOutlet UITableView *cTableLabel;
#end
#implementation CourseFindrViewController
#synthesize jDetails =_jDetails;
-(void)viewWillAppear:(BOOL)animated {
_jDetails = (Jobs *)self.jDetails;
[self.jNameLabel setText:_jDetails.jName];
[self.jDescLabel setText:_jDetails.jDesc];
[self.jEarningsLabel setText:_jDetails.jEarnings];
NSLog(#"%d", _jDetails.jID);
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.jNameLabel = nil;
self.jDescLabel = nil;
self.jEarningsLabel = nil;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSArray *)course;
{
NSString *sqLiteDb = [[NSBundle mainBundle]pathForResource:#"CourseFindr" ofType:#"sqlite"];
sqlite3_stmt *statement;
NSMutableArray *retrieve = [[NSMutableArray alloc] init];
if (sqlite3_open([sqLiteDb UTF8String], &_db) != SQLITE_OK)
{
NSString *query= [NSString stringWithFormat:#"SELECT course. * FROM course INNER JOIN jobsCourse ON jobsCourse.courseID = course.cID WHERE jobsCourse.jobID = %d", _jDetails.jID];
if (sqlite3_prepare_v2(_db, [query UTF8String], -1, &statement, nil) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
int _cID = sqlite3_column_int(statement, 0);
char *cNameChars = (char *) sqlite3_column_text(statement,1);
char *cDescChars = (char *) sqlite3_column_text(statement, 2);
char *cSchoolChars = (char *) sqlite3_column_text (statement, 3);
char *cProgramChars = (char *) sqlite3_column_text(statement, 4);
NSString *_cName =cNameChars?[[NSString alloc]initWithUTF8String:cNameChars]:#"";
NSString *_cDesc = cDescChars?[[NSString alloc]initWithUTF8String:cDescChars]:#"";
NSString *_cSchool = cSchoolChars?[[NSString alloc]initWithUTF8String:cSchoolChars]:#"";
NSString *_cProgram = cProgramChars?[[NSString alloc]initWithUTF8String:cProgramChars]:#"";
Course *courses = [[Course alloc]
initWithCID:_cID
cName:_cName
cDesc:_cDesc
cSchool:_cSchool
cProgram:_cProgram];
[retrieve addObject:courses];
}
sqlite3_finalize(statement);
}
}
return retrieve;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *title1 = _jDetails.jName;
self.navigationItem.title = title1;
}
- (void)dealloc {
}
The code stops here. I added a breakpoint.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.course count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"courseCell"];
NSLog(#"Here.");
Course *courses = [self.course objectAtIndex:indexPath.row];
cell.textLabel.text =courses.cName;
cell.detailTextLabel.text =courses.cSchool;
return cell;
}
And it's still not passing the data to the table.. the table isn't appearing.
You have to add connection between table view and your datasource and delegate.
To do that simple control drag from your table view to view controller and select datasource and do the same but this time select delegate.
You must connect datasource and delegate in the xib. Plese let me know if this answer helped you.
i'm korean my english so simple
very very sorry
please help me
my application example phone book.
two View and tab bar with sqlite3 DB
first view is table view cell list, there are name is linked DB
second view save and find and delete phone book list with SQL query.
i want secondview save data and change tab update data list.
i coded [viewDidAppear] reloadData method
close the application re-open apllication is updated.
but not updated change the tap T_T please help me.
FirstViewController.h
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#interface FirstViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>
{
NSString *path;
NSString *dbName;
NSString *databasePath;
sqlite3 *contactDB;
}
#property (nonatomic) sqlite3 *contactDB_2;
#property (strong,nonatomic) IBOutlet UITableView *myTable;
#property (nonatomic,retain) NSMutableArray *quizs;
-(void)checkAndCreateDatabase;
-(void)readFromDatabase;
#end
FistViewController.m
#import "FirstViewController.h"
#import "person.h"
#implementation FirstViewController
#synthesize contactDB_2,myTable;
#synthesize quizs;
-(void)checkAndCreateDatabase{
NSFileManager *filemgr = [NSFileManager defaultManager];
if([filemgr fileExistsAtPath:databasePath] == NO){
const char *dbPath = [databasePath UTF8String];
if(sqlite3_open(dbPath,&contactDB) == SQLITE_OK){
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,ADRESS TEXT, PHONE TEXT)";
sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg);
sqlite3_close(contactDB);
}
}
}
-(void)readFromDatabase
{
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if(sqlite3_open(dbpath, &contactDB)==SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"SELECT name,phone FROM contacts"];
const char *query_stmt = [querySQL UTF8String];
if(sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL)==SQLITE_OK)
{
while(sqlite3_step(statement)==SQLITE_ROW){
NSString* nameField = [[NSString alloc]initWithUTF8String:(const char*)sqlite3_column_text(statement, 0)];
NSString* phoneField = [[NSString alloc]initWithUTF8String:(const char*)sqlite3_column_text(statement, 1)];
person *persons = [person alloc];
[persons setName:nameField];
[persons setPhone:phoneField];
[quizs addObject:persons];
}
sqlite3_finalize(statement);
[myTable reloadData];
}
sqlite3_close(contactDB);
}
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"전화번호목록", #"전화번호목록");
self.tabBarItem.image = [UIImage imageNamed:#"first"];
}
return self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
pragma mark - View lifecycle
- (void)viewDidLoad
{
dbName = #"contacts2.db";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:dbName];
[self checkAndCreateDatabase];
quizs = [[NSMutableArray alloc] initWithCapacity:100];
[self readFromDatabase];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[myTable delegate];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[quizs removeAllObjects];
[self checkAndCreateDatabase];
[self readFromDatabase];
[myTable reloadData];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return quizs.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* cellIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
person *p = [quizs objectAtIndex:indexPath.row];
NSString *str = [[NSString alloc]initWithFormat:#"%# %#",p.name,p.phone];
cell.textLabel.text = str;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger row = indexPath.row;
NSString *temp = [[NSString alloc]initWithFormat:#"%d번쨰꺼 선택해뜸",row+1];
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:#"터치" message:temp delegate:self cancelButtonTitle:nil otherButtonTitles:#"확인", nil];
[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#end
I want change the tab and update cell list.
Actually you can not insert the data in database in background .So until all data are inserted you have to keep application alive. If all data are saved successfully then please write reloadData code in ViewWillAppear.