MapKit and adding new pins after a MKLocalSearch - xcode

I'm running a MKLocalSearch request and when I find POIs I want to drop a pin based on the coordinates of the POIs I find. NSLog(#"annotations %d",[mapView.annotations count]); returns 0 even with valid coordinates for the POIs
- (void)resultsForButtonTapped:(NSString *)search
{
arrayOfPOIs = [[NSMutableArray alloc] init];
arrayOfAnnotaions = [[NSMutableArray alloc] init];
NSLog(#"%#",search);
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
MKCoordinateRegion region;
request.naturalLanguageQuery = search;
request.region = region;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
localsearch = [[MKLocalSearch alloc] initWithRequest:request];
[localsearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if (error != nil) {
return;
}else{
if ([response.mapItems count] == 0) {
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"No Results",nil)
message:nil
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK",nil) otherButtonTitles:nil] show];
return;
}
for (MKMapItem *item in response.mapItems)
{
NSString *name = item.name;
NSLog(#"%#",name);
[arrayOfPOIs addObject:name];
}
results = response;
NSLog(#"%d",[arrayOfPOIs count]);
for (int i=0; i<[results.mapItems count]; i++) {
MKMapItem* itemPOI = results.mapItems[i];
NSLog(#"Result: %#",itemPOI.placemark.name);
NSLog(#"Result: %#",itemPOI.placemark.name);
MKPlacemark* annotation= [[MKPlacemark alloc] initWithPlacemark:itemPOI.placemark];
MKPointAnnotation *marker = [MKPointAnnotation new];
marker.coordinate = annotation.coordinate;
[mapView addAnnotation:marker];
NSLog(#"annotations %d",[mapView.annotations count]);
}
[self loadTheDataAgain];
}
}];
// NSLog(#"outside the block, the count is %lu",(unsigned long)[arrayOfPOIs count]);
NSLog(#"stuff %#",arrayOfAnnotaions);
}

Related

issue loading core data into uitableview

I have been trying to figure this issue out for days now with no luck, any advice would be greatly appreciated.
I have a uitableviewcontroller that loads data from core data. When the tableview loads, the first 6 (no matter how many objects are actually saved) are loaded. When I begin to scroll down, all of the following cells are labeled "(null)". When I go back up to the top, the data in the original 6 cells are replaced with "(null)". When I logged the contents of the array from the fetch, all of the objects from core data get logged, but when I log the contents of the cell, the first 6 contents get logged, the a long list of rows with (null) get logged.
I've tried a lot of differnet things to debug this, but nothing has worked so far.
Here is the tableviewcontroller file
-(void)viewWillAppear:(BOOL)animated
{
[self setTitle:#"My Safe"];
self.dictionaryWithContent = [[NSMutableDictionary alloc] init];
self.search = #0;
[self fetchDataFromCoreData];
[self.tableView setFrame:CGRectMake(0, 88, self.tableView.bounds.size.width, self.tableView.bounds.size.height)];
self.searchResults = [[NSMutableArray alloc] init];
self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 44.0f)];
UIBarButtonItem *changeViewsButton = [[UIBarButtonItem alloc] initWithTitle:#"Tweets By User"
style:UIBarButtonItemStylePlain
target:self
action:#selector(switchViewControllers)];
self.navigationItem.rightBarButtonItem = changeViewsButton;
self.tableView.delegate = self;
self.tableView.dataSource = self;
// CGRect searchView = CGRectMake(0, 44, self.tableView.bounds.size.width, 44);
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
[self.searchController loadViewIfNeeded];
self.tableView.tableHeaderView = self.searchController.searchBar;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.searchBar.barTintColor = twitter_blue;
self.searchController.delegate = self;
self.searchController.searchBar.delegate = self;
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:animated];
self.navigationController.navigationBar.barTintColor = twitter_blue;
self.navigationController.navigationBar.translucent = NO;
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
[self.navigationController.navigationBar setTitleTextAttributes:#{NSForegroundColorAttributeName : [UIColor whiteColor]}];
}
-(void)fetchDataFromCoreData
{
AppDelegate *del = [[AppDelegate alloc] init];
NSManagedObjectContext *context = del.managedObjectContext;
NSString *entity;
entity = [NSString stringWithFormat:#"Tweet"];
NSFetchRequest *fet = [NSFetchRequest fetchRequestWithEntityName:entity];
NSError *e;
NSArray *array = [context executeFetchRequest:fet error:&e];
self.arrayWithContent = [[NSArray alloc] initWithArray:array];
for (Tweet *t in self.arrayWithContent) {
NSLog(#"array %#", t.messageOfTweet);
}
}
-(void)switchViewControllers
{
PCRSavedTweetByUserTableViewController *vc = [[PCRSavedTweetByUserTableViewController alloc] init];
PCRNavigationBarController *navBarControllerOfSafeSide = [[PCRNavigationBarController alloc] initWithRootViewController:vc];
[self.navigationController presentViewController:navBarControllerOfSafeSide animated:YES completion:nil];
}
#pragma mark Status bar
- (void)willPresentSearchController:(UISearchController *)searchController {
// do something before the search controller is presented
self.navigationController.navigationBar.translucent = YES;
}
-(void)willDismissSearchController:(UISearchController *)searchController
{
self.navigationController.navigationBar.translucent = NO;
searchController = self.searchController;
}
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
searchController = self.searchController;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
self.search = #1;
[self.searchResults removeAllObjects];
NSString *searchBarString = self.searchController.searchBar.text;
for (Tweet *tweet in self.arrayWithContent){
if ([tweet.messageOfTweet containsString:searchBarString] || [tweet.userNameOfTweetUser containsString:searchBarString] || [tweet.whoPosted.name containsString:searchBarString]) {
[self.searchResults addObject:tweet];
}
}
[self.tableView reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[self.searchController.searchBar resignFirstResponder];
self.search = #0;
[self.tableView reloadData];
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
self.searchController.searchBar.text = #"";
}
#pragma mark Table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
return [self.arrayWithContent count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 120.0f;
}
- (PCRTweetFeedCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
PCRTweetFeedCell *cell = [tableView dequeueReusableCellWithIdentifier:#"PCRSavedTweetFeedCell"];
PCRTweet *tweetLocal = [[PCRTweet alloc] init];
if (cell == nil) {
cell = [[PCRTweetFeedCell alloc] initWithTweet:tweetLocal reuseIdentifier:#"PCRSavedTweetFeedCell"];
}
Tweet *tweetForIndex;
NSArray *arrayForCell = [[self.arrayWithContent reverseObjectEnumerator] allObjects];
NSArray *searchArrayForCell = [[self.searchResults reverseObjectEnumerator] allObjects];
if ([self.search isEqual:#0]){
tweetForIndex = [arrayForCell objectAtIndex:indexPath.row];
} else if ([self.search isEqual:#1]){
tweetForIndex = [searchArrayForCell objectAtIndex:indexPath.row];
}
NSString *date = [NSString stringWithFormat:#"%#", tweetForIndex.dateOfTweet];
TweetUser *tweetUser = tweetForIndex.whoPosted;
cell.t = tweetForIndex;
UIImage *imageOfTweetUser;
if (tweetUser.profilePicture) {
imageOfTweetUser = [UIImage imageWithData:tweetUser.profilePicture];
} else {
NSURL *urlWithProfilePicture = [NSURL URLWithString:tweetUser.profilePictureURL];
NSData *dataWithPic = [NSData dataWithContentsOfURL:urlWithProfilePicture];
imageOfTweetUser = [UIImage imageWithData:dataWithPic];
}
self.imageOfTweetUserGlobal = imageOfTweetUser;
cell.tweetMessage.text = tweetForIndex.messageOfTweet;
cell.tweetDate.text = date;
cell.tweetUserNameLabel.text = tweetForIndex.userNameOfTweetUser;
cell.profilePictureOfTwitterUserImageView.image = imageOfTweetUser;
cell.nameForPassing = [NSString stringWithFormat:#"%#'s Tweet", tweetUser.name];
return cell;
}
Well maybe this is your problem.
if ([self.search isEqual:#0]){
I think you are initially fetching the data but than once you init the searchController it starts looking for the searchResults.
The code you are looking is:
if ([self.search isActive]){
I found the solution. I changed
AppDelegate *del = [[AppDelegate alloc] init];
NSManagedObjectContext *context = del.managedObjectContext;
to
AppDelegate *del = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =[del managedObjectContext];
and it works perfectly.

Different table view cell row heights for different size classes?

How can I change this UITableViewController custom class to dynamically change the height of the Table View Cells? I have specified different font sizes for the iPad and iPhone size classes.
(This is a continuation of a previous discussion with #rdelmar)
#import "CREWFoodWaterList.h"
#interface CREWFoodWaterList ()
#end
#implementation CREWFoodWaterList
#define VIEW_NAME #"FoodWaterList" // add to database for this view and notes view
#define VIEW_DESCRIPTION #"Food Water - items to keep available" // to add to the database
#define RETURN_NC #"NCSuggestedContentsMenu" // where to return to when complete processing should be specified there
#define NOTES_TITLE #"Food and Water Notes" // pass to notes VC
#define THIS_NC #"NCFoodWaterList" // pass to next VC (so returns to the NC for this view)
- (IBAction)changedSwitch:(UISwitch *)sender {
if (sender.tag == 0) {
[self saveSwitch: #"switchWater" toValue:[NSNumber numberWithBool:sender.on]];
} else if (sender.tag == 1) {
[self saveSwitch: #"switchCanned" toValue:[NSNumber numberWithBool:sender.on]];
} else if (sender.tag == 2) {
[self saveSwitch: #"switchComfort" toValue:[NSNumber numberWithBool:sender.on]];
} else if (sender.tag == 3) {
[self saveSwitch: #"switchSpecial" toValue:[NSNumber numberWithBool:sender.on]];
}
} // end of changedSwitch
-(void)loadSavedSwitches {
// now set the switches to previously stored values
NSNumber *switchValue;
switchValue = [self getSwitch: #"switchWater"];
if ([switchValue intValue] == 0) {
self.switchWater.on = NO;
} else {
self.switchWater.on = YES;
}
self.textWater.text = [self getDescription:#"switchWater"];
switchValue = [self getSwitch: #"switchCanned"];
if ([switchValue intValue] == 0) {
self.switchCanned.on = NO;
} else {
self.switchCanned.on = YES;
}
self.textCanned.text = [self getDescription:#"switchCanned"];
switchValue = [self getSwitch: #"switchComfort"];
if ([switchValue intValue] == 0) {
self.switchComfort.on = NO;
} else {
self.switchComfort.on = YES;
}
self.textComfort.text = [self getDescription:#"switchComfort"];
// self.textComfort.textColor = [UIColor whiteColor];
switchValue = [self getSwitch: #"switchSpecial"];
if ([switchValue intValue] == 0) {
self.switchSpecial.on = NO;
} else {
self.switchSpecial.on = YES;
}
self.textSpecial.text = [self getDescription:#"switchSpecial"];
}
- (void) createNewSwitches {
// set create all switches and set to off
[self newSwitch: #"switchWater" toValue:#"At least three litres of bottle water per person per day"];
[self newSwitch: #"switchCanned" toValue:#"Canned foods, dried goods and staples"];
[self newSwitch: #"switchComfort" toValue:#"Comfort foods"];
[self newSwitch: #"switchSpecial" toValue:#"Food for infants, seniors and special diets"];
}
// COMMON Methods
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 50;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// set font size for table headers
[[UIDevice currentDevice] model];
NSString *myModel = [[UIDevice currentDevice] model];
NSInteger nWords = 1;
NSRange wordRange = NSMakeRange(0, nWords);
NSArray *firstWord = [[myModel componentsSeparatedByString:#" "] subarrayWithRange:wordRange];
NSString *obj = [firstWord objectAtIndex:0];
if ([obj isEqualToString:#"iPad"]) {
[[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setFont:[UIFont boldSystemFontOfSize:26]];}
else if ([obj isEqualToString:#"iPhone"]) {
[[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setFont:[UIFont boldSystemFontOfSize:16]];
};
[defaults setObject:NOTES_TITLE forKey: #"VCtitle"]; // pass to notes VC
[defaults setObject:VIEW_NAME forKey: #"VCname"]; // pass to notes VC to use to store notes
[defaults setObject:THIS_NC forKey: #"CallingNC"]; // get previous CallingNC and save it for use to return to in doneAction
[self initializeView];
} // end of viewDidLoad
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.tableView reloadData]; // this was necessary to have the cells size correctly when the table view first appeared
}
- (void) initializeView {
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"View" inManagedObjectContext:context];
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(viewName = %#)", VIEW_NAME];
[request setPredicate:pred];
NSError *error = nil;
NSArray * objects = [context executeFetchRequest:request error:&error];
if ([objects count] == 0) { // create new view instance
NSManagedObject * newView;
newView = [NSEntityDescription insertNewObjectForEntityForName:#"View" inManagedObjectContext:context];
[newView setValue:VIEW_NAME forKey:#"viewName"];
[newView setValue:VIEW_DESCRIPTION forKey:#"viewDescription"];
// create all switches and set to off
[self createNewSwitches];
}
// load all switches
[self loadSavedSwitches];
} // end of initializeView
// create a new switch
- (void) newSwitch:(NSString*)switchName toValue:(NSString*)switchDescription {
NSError *error = nil;
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject * newSwitch;
newSwitch = [NSEntityDescription insertNewObjectForEntityForName:#"Switch" inManagedObjectContext:context];
[newSwitch setValue:VIEW_NAME forKey:#"viewName"];
[newSwitch setValue:switchName forKey:#"switchName"];
[newSwitch setValue:switchDescription forKey:#"switchDescription"];
[newSwitch setValue:[NSNumber numberWithInt:0] forKey:#"switchValue"];
if (! [context save:&error])
// NSLog(#"**** START entering %#",VIEW_NAME);
NSLog(#"newSwitch Couldn't save new data! Error:%#", [error description]);
} // end of newSwitch
// read existing switch settings
- (NSNumber *) getSwitch:(NSString*)switchName {
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"Switch" inManagedObjectContext:context];
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(viewName = %#) AND (switchName = %#)", VIEW_NAME, switchName];
[request setPredicate:pred];
// Execute Fetch Request
NSManagedObjectContext * matches = nil;
NSError *fetchError = nil;
NSArray *objects = [appDelegate.managedObjectContext executeFetchRequest:request error:&fetchError];
if (fetchError) {
};
NSNumber *switchValue;
if (! [objects count] == 0) {
matches = objects [0];
switchValue = [matches valueForKey : #"switchValue"];
}
return switchValue;
} // end of getSwitch
- (NSString *) getDescription:(NSString*)switchName {
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"Switch" inManagedObjectContext:context];
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(viewName = %#) AND (switchName = %#)", VIEW_NAME, switchName];
[request setPredicate:pred];
// Execute Fetch Request
NSManagedObjectContext * matches = nil;
NSError *fetchError = nil;
NSArray *objects = [appDelegate.managedObjectContext executeFetchRequest:request error:&fetchError];
if (fetchError) {
// NSLog(#"**** START entering %#",VIEW_NAME);(#"getSwitch Fetch error:%#", fetchError); // no
};
NSString *switchDescription;
if (! [objects count] == 0) {
matches = objects [0];
switchDescription = [matches valueForKey : #"switchDescription"];
}
return switchDescription;
} // end of getDescription
- (void)saveSwitch:(NSString*)switchName toValue:(NSNumber*)newSwitchValue {
CREWAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"Switch" inManagedObjectContext:context]; // get switch entity
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(viewName = %#) AND (switchName = %#)", VIEW_NAME, switchName ];
[request setPredicate:pred];
NSManagedObject *matches = nil;
NSError *fetchError = nil;
NSArray * objects = [context executeFetchRequest:request error:&fetchError];
if (![objects count] == 0) {
matches = objects[0];
}
[matches setValue:newSwitchValue forKey:#"switchValue"];
if (! [context save:&fetchError])
// NSLog(#"**** START entering %#",VIEW_NAME);
NSLog(#"saveSwitch Couldn't save data! Error:%#", [fetchError description]); // perhaps this can be Done later
} // end of saveSwitch
// set alternate cells to different colors
- (UIColor *)getUIColorObjectFromHexString:(NSString *)hexStr alpha:(CGFloat)alpha
{
// Convert hex string to an integer
unsigned int hexint = [self intFromHexString:hexStr];
// Create color object, specifying alpha as well
UIColor *color =
[UIColor colorWithRed:((CGFloat) ((hexint & 0xFF0000) >> 16))/255
green:((CGFloat) ((hexint & 0xFF00) >> 8))/255
blue:((CGFloat) (hexint & 0xFF))/255
alpha:alpha];
return color;
}
// Helper method..
- (unsigned int)intFromHexString:(NSString *)hexStr
{
unsigned int hexInt = 0;
// Create scanner
NSScanner *scanner = [NSScanner scannerWithString:hexStr];
// Tell scanner to skip the # character
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:#"#"]];
// Scan hex value
[scanner scanHexInt:&hexInt];
return hexInt;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *grayishCyan = #"#a3c9ca";
NSString *grayishRed = #"#caa4a3";
UIColor *colorCyan = [self getUIColorObjectFromHexString:grayishCyan alpha:.9];
UIColor *colorPink = [self getUIColorObjectFromHexString:grayishRed alpha:.9];
// // NSLog(#"**** START entering %#",VIEW_NAME);(#"UIColor: %#", colorPink);
if (indexPath.row == 0 || indexPath.row%2 == 0) {
cell.backgroundColor = colorCyan;
}
else {
cell.backgroundColor = colorPink;
}
}
- (IBAction)doneAction:(id)sender {
// NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
UIViewController *viewController = [[UIStoryboard storyboardWithName:#"Main" bundle:nil] instantiateViewControllerWithIdentifier:RETURN_NC]; // previous Navigation controller
[self presentViewController:viewController animated:YES completion:nil];
};
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#end

Block variable gets null outside of block - xcode

Im trying to carry over a block variable and put it in my convenience initializer but the variable returns null, can someone show me the right way of doing it, Thanks, also please check if I have done my NSComparison Result correctly, here's the code,
- (void) retrieveData
{
NSURL *url = [NSURL URLWithString:jsonFile];
NSData *data = [NSData dataWithContentsOfURL:url];
_jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
_salesArray = [[NSMutableArray alloc]init];
for (int i = 0; i < _jsonArray.count; i++) {
NSString *sID = [[_jsonArray objectAtIndex:i] objectForKey:#"id"];
NSString *sName = [[_jsonArray objectAtIndex:i] objectForKey:#"name"];
NSString *sAddress = [[_jsonArray objectAtIndex:i] objectForKey:#"address"];
NSString *sPostcode = [[_jsonArray objectAtIndex:i] objectForKey:#"postcode"];
__block NSString *distance;
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
[geocoder geocodeAddressString:sPostcode completionHandler:^(NSArray *placemarks, NSError *error) {
if (error == nil && placemarks.count > 0) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
CLLocation *myLocation = self.manager.location;
CLLocationDistance miles = [location distanceFromLocation:myLocation];
//this is the variable i want in my convenience init.
distance = [NSString stringWithFormat:#"%.1f m", (miles/1609.344)];
}
}];
[_salesArray addObject:[[sales alloc] initWithSales:sID andName:sName andAddress:sAddress andPostcode:distance]];
}
[_salesArray sortUsingComparator:
^NSComparisonResult(id obj1, id obj2){
sales *p1 = (sales *)obj1;
sales *p2 = (sales *)obj2;
if (p1.postcode > p2.postcode) {
return (NSComparisonResult)NSOrderedDescending;
}
if (p1.postcode < p2.postcode) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}
];
[self.tableView reloadData];
}
Thanks in advance to anyone that can help, this happens to be the last part of my app until completion :)
-[CLGeocoder geocodeAddressString:completionHandler:] runs the completion handler asynchronously and it won't run the block before the rest of that function finishes. distance doesn't "get null"; rather, it hasn't been set yet.
your block is run AFTER the function completes ... doesn't matter if the 'line of code' is after or before the block.
the solution is to have to block call a 'continuation' function:
e.g. instead of - (void) retrieveData
have - (void) beginRetrieveData, which calls the block and then have a - (void) finishRetrieveData, which is called by the block and doesn't run before the block ;)
here is how your code could look:
- (void) beginRetrieveData
{
NSURL *url = [NSURL URLWithString:jsonFile];
NSData *data = [NSData dataWithContentsOfURL:url];
_jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
_salesArray = [[NSMutableArray alloc]init];
for (int i = 0; i < _jsonArray.count; i++) {
NSString *sID = [[_jsonArray objectAtIndex:i] objectForKey:#"id"];
NSString *sName = [[_jsonArray objectAtIndex:i] objectForKey:#"name"];
NSString *sAddress = [[_jsonArray objectAtIndex:i] objectForKey:#"address"];
NSString *sPostcode = [[_jsonArray objectAtIndex:i] objectForKey:#"postcode"];
CLGeocoder *geocoder = [[CLGeocoder alloc]init];
[geocoder geocodeAddressString:sPostcode completionHandler:^(NSArray *placemarks, NSError *error) {
if (error == nil && placemarks.count > 0) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
CLLocation *myLocation = self.manager.location;
CLLocationDistance miles = [location distanceFromLocation:myLocation];
//this is the variable i want in my convenience init.
NSString *distance = [NSString stringWithFormat:#"%.1f m", (miles/1609.344)];
[self finishRetrieveData:distance]; //continue
}
}];
}
}
- (void) finishRetrieveData:(NSString*)distance
{
[_salesArray addObject:[[sales alloc] initWithSales:sID andName:sName andAddress:sAddress andPostcode:distance]];
}

UISearch bar always displays : no result

In my application, I display data from sqlite database in uitableviewsuccessfully and insert UISearchbar and display controller to display search results in an another table, the problem is that when I type a string to search, it always return : no result even if this string exists in that table!!
I think I have something wrong in method
(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText but I don't know exactly what is the problem and how to deal with it !! Here is my code :
MasterViewControllerViewController.m :
#import "MasterViewControllerViewController.h"
#import"MasterViewControllerAppDelegate.h"
#import"SingleStudent.h"
- (void)viewDidLoad {
MasterViewControllerAppDelegate* appDelegate =(MasterViewControllerAppDelegate*)[[UIApplication sharedApplication]delegate];
maListe = [[NSMutableArray alloc] init];
tampon = [[NSMutableArray alloc] init];
[maListe addObjectsFromArray:appDelegate.aryDatabase];
[tampon addObjectsFromArray:maListe];
[super viewDidLoad];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
MasterViewControllerAppDelegate* appDelegate =(MasterViewControllerAppDelegate*)[[UIApplication sharedApplication]delegate];
SingleStudent* sStudent =[appDelegate.aryDatabase objectAtIndex:indexPath.row];
cell.textLabel.text = [sStudent strName];
// Configure the cell.
return cell;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
tampon2 = [[NSMutableArray alloc] init];
[tampon2 addObjectsFromArray:tampon];
[maListe removeAllObjects];
if([searchText isEqualToString:#""])
{
[maListe removeAllObjects];
[maListe addObjectsFromArray:tampon]; // Restitution des données originales
return;
}
for (NSDictionary *dict in tampon2 ){
NSString *name = [NSString stringWithFormat:#"%#", dict];
NSRange range = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (range.location != NSNotFound)
{
if(range.location== 0) // premiere lettre
[maListe addObject:name];}
}}
MasterViewControllerAppDelegate.m
#import "MasterViewControllerAppDelegate.h"
#import "MasterViewControllerViewController.h"
#import "SingleStudent.h"
-(void)updateNames {
databaseName = #"students7.sqlite";
NSArray* documentsPath= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDir =[documentsPath objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];}
-(void)checkAndCreateDatabase {
BOOL success;
NSFileManager* fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:databasePath];
if (success) {
return;
}
NSString* databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
-(void)readWordsFromDatabase{
db = [FMDatabase databaseWithPath:databasePath];
aryDatabase = [[NSMutableArray alloc] init];
[db setLogsErrors:TRUE];
[db setTraceExecution:TRUE];
if (![db open]) {
NSLog(#"failed to open database");
return;
}
else {
NSLog(#"Opened database successfully");
}
FMResultSet* rs = [db executeQuery:#"SELECT * FROM student"];
while ([rs next]) {
int aID = [rs intForColumn:#"id"];
int aPK = [rs intForColumn:#"pk"];
NSString* aName = [rs stringForColumn:#"name"];
SingleStudent* sStudent = [[SingleStudent alloc] initWithData:aPK :aID :aName];
[aryDatabase addObject:sStudent];
[sStudent release];
}
[db close];
}
singleStudent.m
-(id)initWithData:(int)pK :(int)aId :(NSString*)name`
{
self.intPK = pK;
self.intId = aId;
self.strName = name;
return self;}
How can I solve this problem ?
I changed my code to this and it works fine here the changes if someone need it one day:
- (void)viewDidLoad {
maListe = [[NSMutableArray alloc] init];
tampon = [[NSMutableArray alloc] init];
int i;
for (i=0 ; i <= 4; i++) {
MasterViewControllerAppDelegate* appDelegate=(MasterViewControllerAppDelegate*)[[UIApplication sharedApplication]delegate];
SingleStudent* sStudent=[appDelegate.aryDatabase objectAtIndex:i];
[maListe addObject:[sStudent strName]];
}
[tampon addObjectsFromArray:maListe];
[super viewDidLoad];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//MasterViewControllerAppDelegate* appDelegate =(MasterViewControllerAppDelegate*)[[UIApplication sharedApplication]delegate];
//SingleStudent* sStudent =[appDelegate.aryDatabase objectAtIndex:indexPath.row];
//NSString *cellValue = [sStudent strName];
NSString *cellValue = [maListe objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
// Configure the cell.
/*NSString *cellValue = [maListe objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;*/
return cell;}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
tampon2 = [[NSMutableArray alloc] init];
[tampon2 addObjectsFromArray:tampon];
[maListe removeAllObjects];
if([searchText isEqualToString:#""])
{
[maListe removeAllObjects];
[maListe addObjectsFromArray:tampon]; // Restitution des données originales
return;
}
for(NSString *name in tampon2)
{
NSRange r = [name rangeOfString:searchText];
if(r.location != NSNotFound)
{
if(r.location== 0) // premiere lettre
[maListe addObject:name];
}
}
}

Change value of selected field from SQlite3 using Xcode

The purpose when I select a row from a tableView, having data loaded from sqlite, to be capable of changing the value of a certain field.
Manipulating through two views, the first one loads the entire database into a mutable array, and when I press a certain field, I go to another view. In this second view, I have a button. How to obtain the result of when pressing this button the field in the database will change value.
TableviewController know as AuthorVC.m
#import "AuthorVC.h"
#import "Author.h"
#import <sqlite3.h>
#import "SearchVC.h"
//#import "DetailViewController.h"
#import "Details.h"
#implementation AuthorVC
#synthesize theauthors;
#synthesize author;
NSString *authorNAme;
NSString *authorNAme2;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{ searchBar.delegate = (id)self;
[self authorList];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[searchBar release];
searchBar = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (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 == UIInterfaceOrientationPortrait);
}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
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];
}
}
}
[self.tableView reloadData];
}
/*
-(void) showDetailsForIndexPath:(NSIndexPath*)indexPath
{
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;
[self.navigationController pushViewController:vc animated:true];
NSLog(author);
}
*/
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int rowCount;
if(self->isFiltered)
rowCount = filteredTableData.count;
else
rowCount = theauthors.count;
return rowCount;
// Return the number of rows in the section.
//return [self.theauthors count];
}
/*
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
// NSString *Title;
// Author *auth = (Author*)segue.destinationViewController;
Details *dv = (Details*)segue.destinationViewController;
dv.labelText.text = author.title;
NSLog(#"Did Enter prepareForSegue");
// labelText.text = #"Hy";
}
*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"This is the one in authorVc");
static NSString *CellIdentifier = #"AuthorsCell";
UITableViewCell *cell = [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];
// UIAlertView *messageAlert = [[UIAlertView alloc]
// initWithTitle:#"Filtered" message:titleString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
//
// [messageAlert show];
}
else{
author = [theauthors objectAtIndex:indexPath.row];
// UIAlertView *messageAlert = [[UIAlertView alloc]
// initWithTitle:#"Not filtered" message:titleString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
//
// [messageAlert show];
}
cell.textLabel.text = author.name;
// cell.detailTextLabel.text = author.genre;
//NSString *titleString = [[[NSString alloc] initWithFormat:#"Element number : %d",author.name] autorelease];
return cell;
}
-(NSMutableArray *) authorList{
theauthors = [[NSMutableArray alloc] initWithCapacity:1000000];
NSMutableArray * new2 = [[NSMutableArray alloc ] initWithCapacity:100000];
// authorNAme = theauthors.sortedArrayHint.description;
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"data.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: %#", sqlite3_errmsg(db));
}
// const char *sql = "SELECT F_Keyword FROM wordss";
const char *sql = "SELECT * FROM Sheet1";
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) {
Author * author = [[Author alloc] init];
//NSString *authorName = author.name;
author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
author.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,4)];
author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 6)];
new2 = author.genre;
// NSLog(new2);
authorNAme=author.genre;
//NSLog(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;
sqlite3_close(db);
// authorNAme = Nil;
return theauthors;
}
}
- (void)dealloc {
[searchBar release];
[super dealloc];
//[authorNAme release];
}
//- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
//
// /*
// When a row is selected, the segue creates the detail view controller as the destination.
// Set the detail view controller's detail item to the item associated with the selected row.
// */
// if ([[segue identifier] isEqualToString:#"ShowSelectedPlay"]) {
//
// NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow];
// Details *detailViewController = [segue destinationViewController];
// detailViewController.author = [dataController objectInListAtIndex:selectedRowIndex.row];
// }
//}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
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 = vc.author.genre;
authorNAme2 = vc.author.name ;
NSLog(#"This is the details %#",vc.author.genre);
NSLog(#"This is the authorNAme Variable %#" , authorNAme);
vc.labelText.text = vc.author.genre;
vc.text2.text = vc.author.name;
NSString *titleString = [[[NSString alloc] initWithFormat:#"Element number : %d",indexPath.row] autorelease];
UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:authorNAme2 delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[messageAlert show];
[self.navigationController pushViewController:vc animated:true];
/*
//Get the selected country
NSString *selectedAuthors = [theauthors objectAtIndex:indexPath.row];
//NSLog(selectedAuthors);
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
Details *dvController = [storyboard instantiateViewControllerWithIdentifier:#"Details"]; //Or whatever identifier you have defined in your storyboard
//authorNAme = selectedAuthors.description;
//Initialize the detail view controller and display it.
//Details *dvController = [[Details alloc] init/*WithNibName:#"Details" bundle:nil*///];
/*
dvController.selectedAuthors = selectedAuthors;
NSString *titleString = [[[NSString alloc] initWithFormat:#"Element number : %d",indexPath.row] autorelease];
UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:titleString delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[messageAlert show];*/
// NSString *elem = [new2 objectAtIndex:0];
//NSLog(dvController.labelText.text);
// NSString *titleString = [[[NSString alloc] initWithFormat:#"Author title : %d",indexPath.row] autorelease];
// NSString *titleString2 = [[new2 objectAtIndex:indexPath.row] autorelease];
// NSLog(#"this is the selected row , %s",titleString2);
// authorNAme = titleString;
/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! BReak point of SQL Query!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
/*
#try {
NSFileManager *fileMgr2 = [NSFileManager defaultManager];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"dictionary.sqlite"];
//NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"authorsDb2.sqlite"];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"FinalDb.sqlite"];
//NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"xxJuridique-FINAL-OK.sqlite"];
NSString *dbPath2 = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"data.sqlite"];
BOOL success = [fileMgr2 fileExistsAtPath:dbPath2];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath2);
}
if(!(sqlite3_open([dbPath2 UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured: %#", sqlite3_errmsg(db));
}
NSLog(#"access to the second DB is ok");
// const char *sql = "SELECT F_Keyword FROM wordss";
const char *sql2 = "SELECT field7 FROM Sheet1 WHERE field1 = 'titleString' ";
//NSLog(sql2);
sqlite3_stmt *sqlStatement2;
if(sqlite3_prepare(db, sql2, -1, &sqlStatement2, NULL) != SQLITE_OK)
{ NSLog(#"Problem with prepare the db");
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}else{
// while (sqlite3_step(sqlStatement2)==SQLITE_ACCESS_EXISTS) {
NSLog(#"Starting to prepare the result");
Author * author2 = [[Author alloc] init];
NSLog(#"Author 2 created");
author2.genre2 = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement2, 7 )];
NSLog(#"Initialistion of author 2 is ok");
// NSLog(author2.genre);
// authorNAme = author2.genre;
[theauthors addObject:author2];
// }
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}
#finally {
// sqlite3_finalize(sqlStatement);.
// authorNAme = nil;
sqlite3_close(db);
// authorNAme = Nil;
return theauthors;
}
*/
//[self.navigationController pushViewController:dvController animated:YES];
}
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
//return UITableViewCellAccessoryDetailDisclosureButton;
return UITableViewCellAccessoryDisclosureIndicator;
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
[self tableView:tableView didSelectRowAtIndexPath:indexPath];
}
#end
DetailsView controller know as Details.m :
//
// Details.m
// AuthorsApp
//
// Created by georges ouyoun on 7/17/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "Details.h"
#import "Author.h"
#import "AuthorVC.h"
#import <sqlite3.h>
#interface Details ()
#end
#implementation Details
#synthesize Favo;
#synthesize text2;
#synthesize labelText;
#synthesize selectedAuthors;
#synthesize author , infoRequest;
BOOL PAss = NO;
BOOL SElected2 = NO;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// authorNAme = author.genre;
// self.labelText.text =authorNAme;
// Do any additional setup after loading the view.
self.labelText.text = authorNAme;
self.text2.text = authorNAme2;
/* This is where the label text APPearsssssssss */
NSLog(#"Everything is ok now !");
// NSLog(authorNAme);
}
- (void)viewDidUnload
{
// [self setLabelText:nil];
NSLog(#"U have entered view did unload");
[AddBut release];
AddBut = nil;
[self setText2:nil];
[super viewDidUnload];
[self setLabelText:Nil];
[authorNAme release];
// Release any retained subviews of the main view.
}
/*
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"AuthorsCell"]) {
[segue.destinationViewController setLabelText:author.title];
}
}
*/
-(void)viewWillAppear:(BOOL)animated
{
//labelText.text = authorNAme;
NSLog(#"U have entered the viewWillAppear tag");
// detailsLabel.text = food.description;
//authorNAme=Nil;
//[self setauthorName:Nil];
}
/*
-(void) viewDidAppear:(BOOL)animated{
labelText.text = #"This is the DidAppearTag";
NSLog(#"U have entered the viewDidAppear tag");
}
*/
-(void) viewWillDisappear:(BOOL)animated{
NSLog(#"This is the view will disappear tag");
//authorNAme.release;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)dealloc {
[labelText release];
[AddBut release];
[text2 release];
[super dealloc];
}
- (IBAction)AddButClick:(UIButton *)sender {
[AddBut setImage:[UIImage imageNamed:#"apple-logo copy.png"] forState:UIControlStateSelected];
[AddBut setImage:[UIImage imageNamed:#"apple-logo copy.png"] forState:UIControlStateHighlighted];
Favo = [[NSMutableArray alloc] initWithCapacity:1000000];
NSLog(authorNAme);
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"dictionary.sqlite"];
//NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"authorsDb2.sqlite"];
// NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"FinalDb.sqlite"];
//NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"xxJuridique-FINAL-OK.sqlite"];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"data.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: %#", sqlite3_errmsg(db));
}
// const char *sql = "SELECT F_Keyword FROM wordss";
const char *sql = "SELECT * FROM Sheet1";
NSLog(#"Successfully selected from database");
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}else{
NSLog(#"Got in the else tag");
while (sqlite3_step(sqlStatement)==SQLITE_ROW /*&& PAss == NO*/) {
NSLog(#"Got in the while tag");
Author * author = [[Author alloc] init];
NSLog(#"Author initialized");
author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,10)];
NSLog(#"Initialization ok");
// NSLog(author.name);
if(/*author.name == #"NO" &&*/ HighLighted == NO){
//const char *sql2 = "INSERT INTO Sheet1 ";
[AddBut setImage:[UIImage imageNamed:#"apple-logo copy.png"] forState:UIControlStateNormal];
NSLog(#"We have not selected it as fav yet");
// [AddBut setSelected:NO]; //btn changes to normal state
NSLog(#"The button was NOt highlighted and now is");
HighLighted = YES;
// PAss = YES;
// [self release];
break;
}
else
{
NSLog(#"We have selected it as fav");
[AddBut setImage:[UIImage imageNamed:#"apple-logo.png"] forState:UIControlStateNormal];
[AddBut setSelected:NO]; //btn changes to normal state
NSLog(#"The button was highlighted and now is NOt");
HighLighted = NO;
break;
// [self viewDidLoad];
// PAss = YES;
}
// [Favo release];
// NSLog(Favo);
// author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
// author.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
// author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 4)];
// [theauthors addObject:author];
}
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}
#finally {
// sqlite3_finalize(sqlStatement);
sqlite3_close(db);
return Favo;
}
// [AddBut setSelected:YES];
// if(SElected == YES){
// NSLog(#"The button was highlighted and now not");
//
// [AddBut setImage:[UIImage imageNamed:#"apple-logo.png"] forState:UIControlStateNormal];
// [AddBut setSelected:NO]; //btn changes to highlighted åstate
// SElected = NO;
//
// }
//
// else{
//
// [AddBut setSelected:YES]; //btn changes to normal state
// NSLog(#"The button was NOt highlighted and now is");
// SElected = YES;
//
// }
}
#end
First you have to take the values of selected row;
This is in your TABLEVIEWCONTROLLER
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
if(listObject.count!=0){
//you will get the object from the list
ObjectType *selectedObject=(ObjectType*)[listObject objectAtIndex:indexPath.row];
//you can call your view controller (in my example init with nib)
yourDetailViewController = [[YourDetailViewController alloc] initWithNibName:#"YourDetailViewControllerNib" bundle:nil];
//you can set your selected object in order to use it on your detail view controller
yourDetailViewController.objectSelected = selectedObject;
[self.navigationController yourDetailViewController animated:YES];
}
}
And this is in your DETAILVIEWCONTROLLER;
-(void)objectUpdate:(Object*)selectedObject withDBPath:(NSString *)dbPath{
NSError *errMsg;
if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
const char *sql_stmt = [#"CREATE TABLE IF NOT EXISTS iosobjecttable (yourcolumns INTEGER PRIMARY KEY NOT NULL , youranothercolumn VARCHAR)" cStringUsingEncoding:NSUTF8StringEncoding];
if (sqlite3_exec(database, sql_stmt, NULL, NULL, (__bridge void*)errMsg) == SQLITE_OK)
{
// SQL statement execution succeeded
}
if(updateStmt == nil) {
NSString *querySQL = [NSString stringWithFormat:
#"update iosobject set youranothercolumn=%# where p_event_id=%#", object.changedcomlumn,object.objectid];
const char *query_sql = [querySQL UTF8String];
if(sqlite3_prepare_v2(database, query_sql, -1, &updateStmt, NULL) != SQLITE_OK){
NSAssert1(0, #"Error while creating update statement. '%s'", sqlite3_errmsg(database));
//NSLog(#"%#",errMsg);
}
}
#try {
if(SQLITE_DONE != sqlite3_step(updateStmt)){
NSAssert1(0, #"Error while updating data. '%s'", sqlite3_errmsg(database));
//NSLog(#"%#",errMsg);
}
else{
//NSLog(#"updatingupdatingedelementt %#",tEvent.eventid);
}
sqlite3_reset(updateStmt);
}
#catch (NSException* ex) {
//NSLog(#"Error while updating data. '%s'", sqlite3_errmsg(database));
}
}
}
and how you call this function is like this;
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *dbPath=[appDelegate getDBPath];
[self objectUpdate:objectUpdate withDBPath:dbPath];
And in app delegate you have to write getDBPath in app delegate;
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"yourdbname.sqlite"];
}

Resources