Hi I've been trying to test the functionality of the Parse PFQueryTableViewController... however keep receiving the following error:
[Error]: bad characters in classname: (null) (Code: 103, Version: 1.8.0)
I'm using the standard code from the Parse website for doing this and attempting to load the tableviewcontroller from my Pase class: Categories
i.e:
- (instancetype)initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self) { // This table displays items in the Todo class
self.parseClassName = #"Categories";
self.pullToRefreshEnabled = YES;
self.paginationEnabled = YES;
self.objectsPerPage = 25;
}
return self;
}
- (PFQuery *)queryForTable {
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
// If no objects are loaded in memory, we look to the cache first to fill the table
// and then subsequently do a query against the network.
// if (self.objects.count == 0) {
// query.cachePolicy = kPFCachePolicyCacheThenNetwork;
// }
[query orderByDescending:#"createdAt"];
return query;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
object:(PFObject *)object {
static NSString *cellIdentifier = #"categoryCell";
PFTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[PFTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:cellIdentifier];}
// Configure the cell to show todo item with a priority at the bottom
cell.textLabel.text = object[#"Category"];
cell.detailTextLabel.text = object[#"Sequence"];
return cell;
}
Any help would be great fully received, thanks.
There is a problem when creating the parse-supplied vc using interface builder: IB view controllers are initialized with initWithCoder:, not initWithStyle.
One way to cover either kind of initializer is to factor the custom code and implement both, like this:
- (void)customInit {
self.parseClassName = #"Categories";
self.pullToRefreshEnabled = YES;
self.paginationEnabled = YES;
self.objectsPerPage = 25;
}
- (id)initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self) {
[self customInit];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self customInit];
}
return self;
}
Related
I've been working with the PFQueryTableView with images and text. After implementing this code:
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithClassName:#"Story"];
self = [super initWithCoder:aDecoder];
if (self) { // This table displays items in the Todo class
self.parseClassName = #"Story";
self.pullToRefreshEnabled = YES;
self.paginationEnabled = YES;
self.objectsPerPage = 25;
}
return self;
}
- (PFQuery *)queryForTable {
PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
if (self.objects.count == 0) {
query.cachePolicy = kPFCachePolicyCacheThenNetwork;
}
[query orderByDescending:#"createdAt"];
return query;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
object:(PFObject *)object {
static NSString *cellIdentifier = #"cell";
PFTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[PFTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:cellIdentifier];
}
// Configure the cell to show todo item with a priority at the bottom
cell.textLabel.text = object[#"snapDetails"];
PFFile *thumbnail = [object objectForKey:#"snap"];
cell.imageView.image = [UIImage imageNamed:#"placeholder.jpg"];
cell.imageView.file = thumbnail;
return cell;
}
the log gives me this strange warning:
[/BuildRoot/Library/Caches/com.apple.xbs/Sources/CoreUI/CoreUI-
371.4/Bom/Storage/BOMStorage.c:522] is not a BOMStorage file
along with a regular memory warning. Occasionally the app also crashes and XCode displays a message that claims that it has lost connection to my iPhone. When checking the memory usage, as the table goes up or down the memory continues to increase as if the images (which are screen sized) are never released as they go off screen. Any ideas as to what can be happening?
almost in all cases, this is harmless unless your url is wrong.to make the BOMStorage file more serious, you can add this:
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
Besides,you can choose other method to replace:
[image stretchableImageWithLeftCapWidth:0 topCapHeight:0] forState:UIControlStateNormal]
I am trying to create a search bar in Xcode so when you search for an item, you can click on the search result cell and it will go to a view controller but all it is doing now is going to the sea view controller and just displaying the label of the cell i clicked on.
Here is my .m file
#interface ListTableViewController () <UISearchDisplayDelegate>
#property (strong, nonatomic) NSArray *dataArray;
#property (strong, nonatomic) NSArray *searchResults;
#end
#implementation ListTableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.dataArray = [NSArray arrayWithObjects:#"Tomb Raider", #"Little Big Planet", #"Unchanted 3", #"BlackOps 2", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)filterContentForSearchText: (NSString *) searchText
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF CONTAINS[cd] %#", searchText];
self.searchResults = [self.dataArray filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString];
return YES;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
if (tableView == self.tableView) {
return [self.dataArray count];
} else { // (tableView == self.searchDisplayController.searchResultsTableView)
return [self.searchResults count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (tableView == self.tableView) {
cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];
}
return cell;
}
#pragma mark - Table view delegate
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"showDetails"]) {
DetailsViewController *dvc = segue.destinationViewController;
NSIndexPath *indexPath = nil;
if ([self.searchDisplayController isActive]) {
indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
dvc.sendLabel = [self.searchResults objectAtIndex:indexPath.row];
return;
} else{
indexPath = [self.tableView indexPathForSelectedRow];
dvc.sendLabel = [self.dataArray objectAtIndex:indexPath.row];
return;
}
}
}
#end
Thanks, anything will help.
You must implement this delegate method :
// Method returns the clicked row.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
YourPushedViewController *ypVC = [[YourPushedViewController alloc] initWithNibName:#"YourPushedViewController" bundle:nil];
ypVC.selectedText = myResultArray[indexPath.row];
[self.navigationController pushViewController:ypVC animated:YES];
}
That method is response for selecting row and passing selected result to another view.
This is hint for you :Passing Data between View Controllers
I am an Objective C newbie (background includes perl/php/VB...non object oriented). I am trying to learn Objective C and xcode and working on a project that involves data as a test case. It uses story board.
I have a database class, a class for single items and a class for multiple items and a view controller. I have deleted the default scene and added a table view controller and selected the controller as it class. I can get the data to dump in NSlog, but am stuck at getting it to display on the Table View. Here is what I have (omitted are the single item h and m as well as the AppDelegate files):
CarbDatabase.h:
#import <Foundation/Foundation.h>
#import "/usr/include/sqlite3.h"
#interface CarbDatabase : NSObject {
sqlite3 *_database;
}
+ (CarbDatabase*)database;
- (NSArray *)FoodItems;
#end
CarbDatabase.m:
#import "FoodItem.h"
#import "CarbDatabase.h"
#implementation CarbDatabase
static CarbDatabase *_database;
+ (CarbDatabase*)database {
if (_database == nil) {
_database = [[CarbDatabase alloc] init];
}
return _database;
}
- (id)init {
if ((self = [super init])) {
NSString *sqLiteDb = [[NSBundle mainBundle] pathForResource:#"food" ofType:#"sqlite3"];
if (sqlite3_open([sqLiteDb UTF8String], &_database) != SQLITE_OK) {
NSLog(#"Failed to open database!");
}
}
return self;
}
- (NSArray *)FoodItems {
NSMutableArray *retval = [[NSMutableArray alloc] init];
NSString *query = #"SELECT ID, LongDesc, ShortDesc, Carb, Sugar, lipid, GrmWt1, GrmWtDesc1, GrmWt2, GrmWtDesc2 FROM food ORDER BY LongDesc";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil)
== SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
int uniqueID = sqlite3_column_int(statement, 0);
char *LongDescChars = (char *) sqlite3_column_text(statement, 1);
char *ShortDescChars = (char *) sqlite3_column_text(statement, 2);
int Carb = sqlite3_column_int(statement, 3);
int Sugar = sqlite3_column_int(statement, 4);
int Lipid = sqlite3_column_int(statement, 5);
int GrmWt1 = sqlite3_column_int(statement, 6);
char *GrmWtDesc1Chars = (char *) sqlite3_column_text(statement, 7);
int GrmWt2 = sqlite3_column_int(statement, 8);
char *GrmWtDesc2Chars = (char *) sqlite3_column_text(statement, 9);
NSString *LongDesc = [[NSString alloc] initWithUTF8String:LongDescChars];
NSString *ShortDesc = [[NSString alloc] initWithUTF8String:ShortDescChars];
NSString *GrmWtDesc1 = [[NSString alloc] initWithUTF8String:GrmWtDesc1Chars];
NSString *GrmWtDesc2 = [[NSString alloc] initWithUTF8String:GrmWtDesc2Chars];
FoodItem *info = [[FoodItem alloc] initWithuniqueID:uniqueID LongDesc:LongDesc ShortDesc:ShortDesc Carb:Carb Sugar:Sugar Lipid:Lipid GrmWt1:GrmWt1 GrmWtDesc1:GrmWtDesc1 GrmWt2:GrmWt2 GrmWtDesc2:GrmWtDesc2];
[retval addObject:info];
}
sqlite3_finalize(statement);
}
else
{
NSLog (#"statement failed");
}
return retval;
}
#end
Controller.h:
#import <UIKit/UIKit.h>
#interface CarbViewController : UITableViewController
#property (nonatomic, retain) NSArray *FoodItems;
#end
Controller.m:
#import "CarbViewController.h"
#import "CarbDatabase.h"
#import "FoodItem.h"
#import "/usr/include/sqlite3.h"
#interface CarbViewController ()
#end
#implementation CarbViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
self.FoodItems = [CarbDatabase database].FoodItems;
self.title = #"Food Items %d",[_FoodItems count];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_FoodItems count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"FoodItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
int rowcount = indexPath.row;
FoodItem *info = [_FoodItems objectAtIndex:indexPath.row];
cell.textLabel.text = info.ShortDesc;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%d Carbs per 100 Grams", info.Carb];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#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
I don't know if there are more problems, but
numberOfSectionsInTableView: should return 1, not 0 (otherwise the table view
will always be empty).
Alternatively, don't implement that method, as the default value is 1.
I'm trying to parse JSON feed from reddit.com and then display it in a tableview. The JSON looks like this:
{
kind: Listing
data: {
modhash: 3lmt2d4hq6797af804da91bde566bd067ddee68e1e7f8e0dda
children: [
{
kind: t3
data: {
domain: imgur.com
banned_by: null
media_embed: { }
subreddit: funny
selftext_html: null
selftext:
likes: null
link_flair_text: null
id: 16e9so
clicked: false
title: I left my dog unattended with the 2 year old...
num_comments: 166
score: 2213
approved_by: null
over_18: false
hidden: false
thumbnail: http://c.thumbs.redditmedia.com/DaoiOlvtdjaPBG3n.jpg
subreddit_id: t5_2qh33
edited: false
link_flair_css_class: null
author_flair_css_class: null
downs: 2481
saved: false
is_self: false
permalink: /r/funny/comments/16e9so/i_left_my_dog_unattended_with_the_2_year_old/
name: t3_16e9so
created: 1357963292
url: http://imgur.com/zGMxP
author_flair_text: null
author: ShaneNickerson
created_utc: 1357934492
media: null
num_reports: null
ups: 4694
}
...more items here
}
And here's my tableview controller code:
#import "mainRedditFunViewController.h"
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define kjsonURL [NSURL URLWithString: #"http://reddit.com/r/funny/.json"
#interface mainRedditFunViewController ()
#end
#implementation mainRedditFunViewController
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://reddit.com/r/funny/.json"]];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (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] ;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
NSDictionary *appsdict = [jsonResults objectAtIndex:indexPath.row];
NSString *VersionString = [appsdict objectForKey:#"url"];
NSString *priceString = [appsdict objectForKey:#"author"];
NSURL *imageURL = [NSURL URLWithString:[appsdict objectForKey:#"thumbnail"]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *imageLoad = [[UIImage alloc] initWithData:imageData];
cell.textLabel.text = [appsdict objectForKey:#"title"];
cell.detailTextLabel.text = [NSString stringWithFormat:#"URL: %# Author: $ %# USD",VersionString,priceString];
cell.imageView.image = imageLoad;
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [jsonResults count];
}
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
jsonResults = [json objectForKey:#"data.children"];
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
However, the output is completly empty. Is there anyway I could fix it? I tried it before with another (smaller) feed and it worked fine. I'm sure if I'm doing the JSONPath formatting correctly, since I'd look like that:
-kind
->data
->children
->data (my items)
->data
->data
...
I'd appreciate any help I get!
Im sorry that this answer is late! hope that it is still needed...
I have altered your code a little bit to access the sub levels of the returned Json results.
You certainly have the right Idea but just need a few more dictionaries in your fetchedData method. If you add these dictionaries in you method underneath your NSJSONSerialization;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
//NSArray *Fullarray = [[NSArray alloc] initWithObjects:json, nil];
_jsonResult = [[NSMutableArray alloc] init];
NSDictionary *dataDict = [json objectForKey:#"data"];
NSDictionary *chilrenDict = [dataDict objectForKey:#"children"];
for (NSDictionary *informationFromChild in chilrenDict) {
NSLog(#"chil %#", chilrenDict);
[_jsonResult addObject:chilrenDict];
}
Then in your tableView cellForRow change your appsDict to this
NSDictionary *appsdict = [[_jsonResult objectAtIndex:indexPath.row] objectForKey:#"data"];
That should fix up the code and populate the tableView...
You can run a check on this too by checking
NSLog(#"count %i", [_jsonResult count]);
Let me know if this has been of help, happy coding. T
I have a Master/Details Application.By default, we have the MasterViewController attached to a TableViewController, in addition, i have attached it to an Sqlite database and all the data are showing correctly as they should. So i added a UISearchBar, in order to search upon all the items ; Search functionality's were working fine but the only bug was, the search bar disappears when scrolling down. So as a solution, i removed the TableViewController and created a simple UIVIewController and added a TableView , TableViewCell and a search bar in order to keep the search bar fix on top of the View as suggested by many people.Now the difference between those two concepts is, the TableViewController (First Case) loads the whole data in the cells once the application loads, when the ViewController ( Second Case , with a tableView , tableViewCell and a searchBar) does not load anything at startup, It loads the different elements when the user start writing a word in the searchBar. How can i force the tableView to load all Elements at startup, just like if you have a TableViewCOntroller?
This is my code :
//
// MasterViewController.m
#import "MasterViewController.h"
#import "DetailViewController.h"
#import <sqlite3.h>
#import "Author.h"
#interface MasterViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
#end
#implementation MasterViewController
NSString *authorNAme , *authorNAme2;
#synthesize tableView;
#synthesize searchWasActive;
#synthesize detailViewController = _detailViewController;
#synthesize fetchedResultsController = __fetchedResultsController;
#synthesize managedObjectContext = __managedObjectContext;
#synthesize theauthors;
NSString *PathDB;
-(BOOL)canBecomeFirstResponder{
return YES;
}
- (void)awakeFromNib
{
// self.clearsSelectionOnViewWillAppear = NO;
self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
[super awakeFromNib];
}
- (void)viewDidLoad
{
// [self numberOfSectionsInTableView:tableView];
//[self tableView:tableView willDisplayCell:[self.tableView dequeueReusableCellWithIdentifier:#"Cell"] forRowAtIndexPath:0];
//[self.tableView
searchBar.delegate = (id)self;
// [self.tableView reloadData];
// [self configureCell:#"Cell" atIndexPath:0];
[self authorList];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];
}
- (void)viewDidUnload
{
[self setTableView:nil];
tableView = nil;
searchBar = nil;
[self setSearchWasActive:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)insertNewObject:(id)sender
{
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
[newManagedObject setValue:[NSDate date] forKey:#"timeStamp"];
// Save the context.
NSError *error = nil;
if (![context save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
//[self authorList];
// [filteredTableData release];
//[self.tableView reloadData];
NSLog(#"Cancel Button Clicked");
// Scroll to top
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
self.searchDisplayController.searchBar.text =#" ";
}
- (void) searchBarTextDidBeginEditing:(UISearchBar *)sender
{
[self.tableView reloadData];
searchBar.showsCancelButton=NO;
}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
searchBar.showsCancelButton=NO;
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = true;
filteredTableData = [[NSMutableArray alloc] init];
for (Author* author in theauthors)
{ //[NSPredicate predicateWithFormat:#"SELECT * from books where title LIKE %#", searchBar.text];
NSRange nameRange = [author.name rangeOfString:text options:NSAnchoredSearch];
NSRange descriptionRange = [author.genre rangeOfString:text options:NSAnchoredSearch];
if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound)
{
[filteredTableData addObject:author];
NSLog(#"Item Added is %#" , author.name);
}
}
}
[self.tableView reloadData];
}
#pragma mark - Table View methods
-(NSMutableArray *) authorList{
[self numberOfSectionsInTableView:tableView];
theauthors = [[NSMutableArray alloc] initWithCapacity:1000000];
// NSMutableArray * new2 = [[NSMutableArray alloc ] initWithCapacity:100000];
// authorNAme = theauthors.sortedArrayHint.description;
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSLog(#"Before the dbpath variable");
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"dictionary_native.sqlite"];
NSLog(#"After the dbpath variable");
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"1");
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
NSLog(#"Database correctly located");
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"2");
NSLog(#"An error has occured: %#", sqlite3_errmsg(db));
}
NSLog(#"Database correctly opened");
// const char *sql = "SELECT F_Keyword FROM wordss";
const char *sql = "SELECT * FROM wordss";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}else{
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
// NSLog(#"entered the while statement");
Author * author = [[Author alloc] init];
// // NSLog(#"Author initialised");
//
author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
// NSLog(#"this is the author.name %#" , author.name);
author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 2)];
//
// authorNAme=author.genre;
//
[theauthors addObject:author];
}
// authorNAme = author.genre;
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}
#finally {
// sqlite3_finalize(sqlStatement);.
// authorNAme = nil;
// authorNAme = Nil;
return theauthors;
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// return [[self.fetchedResultsController sections] count];
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
// return [sectionInfo numberOfObjects];
int rowCount;
if(self->isFiltered)
rowCount = filteredTableData.count;
else
rowCount = theauthors.count;
NSLog(#"This is the number of rows accepted %i" , rowCount);
return rowCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"Cell"];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
int rowCount = indexPath.row;
Author *author = [self.theauthors objectAtIndex:rowCount];
if(isFiltered){
author = [filteredTableData objectAtIndex:indexPath.row];
}
else{
author = [theauthors objectAtIndex:indexPath.row];
}
cell.textLabel.text = author.name;
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
NSError *error = nil;
if (![context save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// The table view should not be re-orderable.
return NO;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// NSManagedObject *object = [[self fetchedResultsController] objectAtIndexPath:indexPath];
// self.detailViewController.detailItem = object;
// DetailViewController* vc ;
MasterViewController *author;
NSLog(#"This is the showDetailsForIndexPath");
[self->searchBar resignFirstResponder];
// Details* vc = [self.storyboard instantiateViewControllerWithIdentifier:#"Details"];
// AuthorVC* author;
if(isFiltered)
{
author = [filteredTableData objectAtIndex:indexPath.row];
}
else
{
author = [theauthors objectAtIndex:indexPath.row];
}
//vc.author = author;
authorNAme = author.genre;
authorNAme2 = author.name ;
// author = [theauthors objectAtIndex:indexPath.row];
NSLog(#"This is the author.genre %#" , author.genre);
//vc.author.genre = author.genre;
authorNAme = author.genre;
authorNAme2 = author.name;
//NSLog(#"This is the details %#",vc.author.genre);
NSLog(#"This is the authorNAme Variable %#" , authorNAme);
self.detailViewController.detailItem = authorNAme;
self.detailViewController.detailItem2 = authorNAme2;
}
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil) {
return __fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Event" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"timeStamp" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:#"Master"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __fetchedResultsController;
}
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type) {
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
// UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView endUpdates];
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
// In the simplest, most efficient, case, reload the table view.
[self.tableView reloadData];
}
*/
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
// NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
// cell.textLabel.text = [[object valueForKey:#"timeStamp"] description];
}
#end
Any help Will be highly appreciated...Thank you for taking the time.
If the tableview is in xib link it to correct object and set delegate and datasource.