how to get the new latitudes and longitudes while moving Using Xcode - xcode6

I am developing an App that records the latitude and longitudes for every 10mts and save them in server , so far I am able to get the current location of the person but the values are not changing, I used timers too
below is my code
// FamilyTrackerViewController.m
// FamilyTracker
//
// Created by Osmosys on 03/02/15.
// Copyright (c) 2015 Osmosys. All rights reserved.
//
#import "FamilyTrackerViewController.h"
#interface FamilyTrackerViewController ()
#end
#implementation FamilyTrackerViewController
#synthesize CLController;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
-(void)viewDidAppear:(BOOL)animated:(BOOL)animated
{
CLController = [[OSMGPSLocationTrackingDelegate alloc] init];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
_txtMobileNumber.delegate=self;
double score = xxxxxxxx429;
// NSString *str=#"xxxxxx429";
//[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithString:str] forKey:#"HIGHSCORE"];
// str=[[[NSUserDefaults standardUserDefaults] objectForKey:#"HIGHSCORE"] stringValue];
// score = [[[NSUserDefaults standardUserDefaults] objectForKey:#"HIGHSCORE"] doubleValue];
_txtMobileNumber.text= #"XXXXXX429";
#pragma mark NextPrevios Methods
UIToolbar *objToolbar=[[UIToolbar alloc]init];
// objToolbar.tintColor = [UIColor colorWithRed:136.0/255.0 green:6.0/255.0 blue:1.0/255.0 alpha:1.0];
// [objToolbar setBackgroundImage:[UIImage imageNamed:#"navigations_iPhone.png"] forToolbarPosition:UIToolbarPositionBottom barMetrics:UIBarMetricsDefault];
// [objToolbar insertSubview:[[UIImageView alloc]initWithImage:[UIImage imageNamed:#"navigations_iPhone.png"]] atIndex:0];
// objToolbar.barStyle = UIBarStyleBlack;
UIBarButtonItem *objBarbtndone=[[UIBarButtonItem alloc]init];
// objBarbtndone.tintColor = [UIColor colorWithRed:136.0/255.0 green:6.0/255.0 blue:1.0/255.0 alpha:1.0];
objBarbtndone.style=UIBarButtonItemStyleBordered;
objBarbtndone.title=#"Done";
objBarbtndone.target=self;
objBarbtndone.action=#selector(btnBarDone);
UIBarButtonItem *objBarbtnPre=[[UIBarButtonItem alloc]init];
objBarbtnPre.title=#"Previous";
// objBarbtnPre.tintColor = [UIColor colorWithRed:136.0/255.0 green:6.0/255.0 blue:1.0/255.0 alpha:1.0];
objBarbtnPre.style=UIBarButtonItemStyleBordered;
objBarbtnPre.target=self;
objBarbtnPre.action=#selector(btnBarPre);
UIBarButtonItem *objBarbtnNext=[[UIBarButtonItem alloc]init];
// objBarbtnNext.tintColor = [UIColor colorWithRed:136.0/255.0 green:6.0/255.0 blue:1.0/255.0 alpha:1.0];
objBarbtnNext.style=UIBarButtonItemStyleBordered;
objToolbar.frame=CGRectMake(0, 0, 320, 44);
objBarbtnNext.title=#"Next";
objBarbtnNext.target=self;
objBarbtnNext.action=#selector(btnBtnNxt);
if([[UIDevice currentDevice].systemVersion floatValue]<7.0)
{
objBarbtnNext.tintColor = [UIColor colorWithRed:136.0/255.0 green:6.0/255.0 blue:1.0/255.0 alpha:1.0];
objBarbtnPre.tintColor = [UIColor colorWithRed:136.0/255.0 green:6.0/255.0 blue:1.0/255.0 alpha:1.0];
objBarbtndone.tintColor = [UIColor colorWithRed:136.0/255.0 green:6.0/255.0 blue:1.0/255.0 alpha:1.0];
}
UIBarButtonItem *objBarbtnSpace= [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
objToolbar.items=[NSArray arrayWithObjects:objBarbtnPre,objBarbtnNext,objBarbtnSpace,objBarbtndone, nil];
_txtMobileNumber.inputAccessoryView=objToolbar;
//CLController = [[OSMGPSLocationTrackingDelegate alloc] init];
//CLController.delegate = self;
//[CLController.locMgr startUpdatingLocation];
locationManager = [[CLLocationManager alloc] init];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager setDelegate:self];
[locationManager setDistanceFilter:2.0];
[locationManager startUpdatingLocation];
[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(useLocation) userInfo:nil repeats:YES];
}
-(void)useLocation{
NSLog(#"%#",[locationManager location]);
//CLController = [[OSMGPSLocationTrackingDelegate alloc] init];
// CLController.delegate = self;
// [CLController.locMgr startUpdatingLocation];
locationManager1 = [[CLLocationManager alloc] init];
[locationManager1 setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager1 setDelegate:self];
[locationManager1 setDistanceFilter:2.0];
[locationManager1 startUpdatingLocation];
_lbllogitudes.text= [NSString localizedStringWithFormat:#"%.18f",locationManager1.location.coordinate.longitude];
_lblLatitudes.text= [NSString localizedStringWithFormat:#"%.18f",locationManager1.location.coordinate.latitude];
[locationManager1 stopUpdatingLocation];
}
-(void)btnBarDone
{
[_txtMobileNumber resignFirstResponder];
}
//Loading the GPS location data to the apps loclable string
-(void)locationUpdate:(CLLocation *)location
{
locLabel= [location description];
_lbllogitudes.text= [NSString localizedStringWithFormat:#"%.15f",location.coordinate.longitude];
_lblLatitudes.text= [NSString localizedStringWithFormat:#"%.15f",location.coordinate.latitude];
// _lbllogitudes.text= [NSString localizedStringWithFormat:#"%f",location.coordinate.longitude];
// _lblLatitudes.text= [NSString localizedStringWithFormat:#"%f",location.coordinate.latitude];
}
//If any error occurs.
- (void)locationError:(NSError *)error {
locLabel = [error description];
//[self.GPSOutput setText:locLabel];
}
//Closing the GPS device and service.
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
//Stoping the GPS data
[CLController.locMgr stopUpdatingLocation];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end

you should use the CLLocationManager's delegate:
locationManager:didUpdateLocations:
you will get an array of CLLocation, just extract your current coordinate from its last object.
You don't need timer, the delegate will automatically send location updates to you.

Related

Unrecognized selector issue

This is the code:
#interface CreateAccountViewController : UIViewController<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
{
UIToolbar *keyboardToolbar;
NSDate *birthdate;
UIActionSheet *dateSheet;
}
#property(strong, nonatomic) IBOutlet UITextField *txtFirstName;
#property(strong, nonatomic) IBOutlet UITextField *txtLastName;
#property(strong, nonatomic) IBOutlet UITextField *txtGender;
#property(strong, nonatomic) IBOutlet UITextField *txtBirthdate;
#property(strong, nonatomic) IBOutlet UITextField *txtEmail;
-(void)resignKeyboard:(id)sender;
-(void)gotoPreviousField:(id)sender;
-(void)gotoNextField:(id)sender;
-(void)setBirth;
-(void)dismissDateSet;
-(void)gotoPreviousBirthdate;
-(void)gotoNextBirthdate;
#end
#implementation CreateAccountViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
[[[keyboardToolbar items] objectAtIndex:0] setEnabled:YES];
[[[keyboardToolbar items] objectAtIndex:1] setEnabled:YES];
if([textField isEqual:self.txtFirstName])
{
[[[keyboardToolbar items] objectAtIndex:0] setEnabled:NO];
}
else if([textField isEqual:self.txtEmail])
{
[[[keyboardToolbar items] objectAtIndex:0] setEnabled:NO];
}
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if([textField isEqual:self.txtBirthdate])
{
[self setBirth];
return NO;
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view
if(keyboardToolbar==nil)
{
keyboardToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
UIBarButtonItem *btnPrevious = [[UIBarButtonItem alloc] initWithTitle:#"Previous" style:UIBarButtonItemStyleBordered target:self action:#selector(gotoPreviousField:)];
UIBarButtonItem *btnNext = [[UIBarButtonItem alloc] initWithTitle:#"Next" style:UIBarButtonItemStyleBordered target:self action:#selector(gotoNextField:)];
UIBarButtonItem *btnExtraSpace= [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *btnDone=[[UIBarButtonItem alloc] initWithTitle:#"Done" style:UIBarButtonItemStyleDone target:self action:#selector(resignKeyboard:)];
[keyboardToolbar setItems:[[NSArray alloc] initWithObjects:btnPrevious, btnNext, btnExtraSpace, btnDone, nil]];
}
}
-(void) resignKeyboard:(id)sender
{
if([self.txtFirstName isFirstResponder])
{
[self.txtFirstName resignFirstResponder];
}
else if([self.txtLastName isFirstResponder])
{
[self.txtLastName resignFirstResponder];
}
else if([self.txtGender isFirstResponder])
{
[self.txtGender resignFirstResponder];
}
else if([self.txtBirthdate isFirstResponder])
{
[self.txtBirthdate resignFirstResponder];
}
else if([self.txtEmail isFirstResponder])
{
[self.txtEmail resignFirstResponder];
}
}
-(void) gotoPreviousField:(id)sender
{
if([self.txtFirstName isFirstResponder])
{
[self.txtEmail becomeFirstResponder];
}
else if([self.txtLastName isFirstResponder])
{
[self.txtFirstName becomeFirstResponder];
}
else if([self.txtGender isFirstResponder])
{
[self.txtLastName becomeFirstResponder];
}
else if([self.txtEmail isFirstResponder])
{
[self.txtBirthdate becomeFirstResponder];
}
}
-(void)gotoNextField:(id)sender
{
if([self.txtFirstName isFirstResponder])
{
[self.txtLastName becomeFirstResponder];
}
else if([self.txtLastName isFirstResponder])
{
[self.txtGender becomeFirstResponder];
}
else if([self.txtGender isFirstResponder])
{
[self.txtBirthdate becomeFirstResponder];
}
else if([self.txtEmail isFirstResponder])
{
[self.txtFirstName becomeFirstResponder];
}
}
-(void)setBirth
{
dateSheet=[[UIActionSheet alloc] initWithTitle:nil delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
[dateSheet setActionSheetStyle:UIActionSheetStyleDefault];
CGRect pickerFrame=CGRectMake(0, 44, 0, 0);
UIDatePicker *birthDayPicker=[[UIDatePicker alloc] initWithFrame:pickerFrame];
[birthDayPicker setDatePickerMode:UIDatePickerModeDate];
[dateSheet addSubview:birthDayPicker];
UIToolbar *birthDayToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, dateSheet.bounds.size.width, 44)];
[birthDayToolbar setBarStyle:UIBarStyleBlackTranslucent];
[birthDayToolbar sizeToFit];
UIBarButtonItem *btnPrevious = [[UIBarButtonItem alloc] initWithTitle:#"Previous" style:UIBarButtonItemStyleBordered target:self action:#selector(gotoPreviousBirthdate:)];
UIBarButtonItem *btnNext = [[UIBarButtonItem alloc] initWithTitle:#"Next" style:UIBarButtonItemStyleBordered target:self action:#selector(gotoNextBirthdate:)];
UIBarButtonItem *btnExtraSpace= [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *btnDone=[[UIBarButtonItem alloc] initWithTitle:#"Done" style:UIBarButtonItemStyleDone target:self action:#selector(dismissDateSet:)];
[birthDayToolbar setItems:[[NSArray alloc] initWithObjects:btnPrevious, btnNext, btnExtraSpace, btnDone, nil]];
[dateSheet addSubview:birthDayToolbar];
[dateSheet showInView:self.view];
[dateSheet setBounds:CGRectMake(0, 0, 320, 485)];
}
-(void)dismissDateSet
{
NSArray *listOfViews = [dateSheet subviews];
for(UIView *subView in listOfViews)
{
if([subView isKindOfClass:[UIDatePicker class]])
{
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM/dd/yyyy"];
self.txtBirthdate.text=[dateFormatter stringFromDate:[(UIDatePicker*)subView date]];
}
}
}
-(void)gotoPreviousBirthdate
{
[self dismissDateSet];
[self.txtGender becomeFirstResponder];
}
-(void)gotoNextBirthdate
{
[self dismissDateSet];
[self.txtEmail becomeFirstResponder];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CreateCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UITextField *textField = [[UITextField alloc] init];
textField.enablesReturnKeyAutomatically = YES;
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
textField.clearButtonMode=UITextFieldViewModeWhileEditing;
textField.delegate=self;
CGRect aRect=CGRectMake(10, 10.f, CGRectGetWidth(cell.bounds)-40.f, 30.f );
textField.frame = aRect;
if(indexPath.row==0)
{
textField.placeholder = #"First name";
self.txtFirstName=textField;
}
else if(indexPath.row==1)
{
textField.placeholder = #"Last name";
self.txtLastName=textField;
}
else if(indexPath.row==2)
{
textField.placeholder = #"Gender";
self.txtGender=textField;
}
else if(indexPath.row==3)
{
textField.placeholder = #"Date of birth";
self.txtBirthdate=textField;
}
else
{
textField.placeholder = #"Email";
self.txtEmail=textField;
}
[cell.contentView addSubview:textField];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
textField.inputAccessoryView=keyboardToolbar;
return cell;
}
#end
If i press the Previous button from the date picker toolbar i get this exception:
[CreateAccountViewController gotoPreviousBirthdate:]: unrecognized selector sent to instance
If i press the Next button from the date picker toolbar i get this exception:
[CreateAccountViewController gotoNextBirthdate:]: unrecognized selector sent to instance
If i press the Done button from the date picker toolbar i get this exception:
[CreateAccountViewController dismissDateSet:]: unrecognized selector sent to instance
It seems that i am making the same mistake 3 times but i can't quite figure out what is that.
Thanks
Your setting the target selector to be:
#selector(gotoPreviousBirthdate:)
But you declare it as:
-(void)gotoPreviousBirthdate;
Remove the : in the selector as #selector(gotoPreviousBirthdate) since you're not taking an argument, or change the declaration to be -(void)gotoPreviousBirthday:(id)sender.
Then repeat for the other two.
You are calling the methods as if they are class methods, but they are declared as instance methods in your interface. Also the invocation of the selector is incorrect.
Create an instance of the class first:
CreateAccountViewController *vc = [[CreateAccountViewController alloc] init]; //Something like this
Then you can call the instance methods:
[vc gotoPreviousBirthday]; //Note no trailing colon!
Or, if you declared the method as
+(void)gotoPreviousBirthdate;
note the + in the signature - then you could call the method as your code shows.
This is a pretty fundamental concept in Objective-C so I would recommend you read the documentation first. Apple Objective-C Primer

a specific instance of insertsubview at index not working in ios 6.0

I'm testing my ios app that has a deployment target of 5.0 and a base SDK of 6.1.
Everything works fine in ios 5.0, and ios 5.1, but in ios 6.0 I'm having an issue with inserting a subview at index. The subview is a tableview and the parent view is an uialertview that was created as a special class "UIAlertTableView." The alertview appears, but there appears to be nothing inserted. Before this, I had fixed an autorotation issue of the superview (which is in landscape) because, as it is well known ios 6.0 handles rotation differently, so now my superview appears correctly, but as I said, this alertview pops up with no table now. Am I suppose to be fixing autorotation issues for the tableview as well as the superview? I didn't think this would be necessary since the tableview is not declared in the imported class, is is declared within the parent viewcontroller. Or could this be because of some method that was deprecated in ios 6.0?
/*UIAlertTableView.m (the imported object class)*/
#interface UIAlertView (private)
- (void)layoutAnimated:(BOOL)fp8;
#end
#implementation UIAlertTableView
#synthesize tableWidth;
#synthesize tableHeight;
#synthesize lowestView;
#synthesize kTablePadding;
#synthesize alertDelegate;
- (void)layoutAnimated:(BOOL)fp8 {
[super layoutAnimated:fp8];
[self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y - tableExtHeight/2, self.frame.size.width, self.frame.size.height + tableExtHeight)];
// We get the lowest non-control view (i.e. Labels) so we can place the table view just below
int i = 0;
while (![[self.subviews objectAtIndex:i] isKindOfClass:[UIControl class]]) {
lowestView = [self.subviews objectAtIndex:i];
i++;
}
tableWidth = 262.0f;
for (UIView *sv in self.subviews) {
// Move all Controls down
if ([sv isKindOfClass:[UIControl class]]) {
sv.frame = CGRectMake(sv.frame.origin.x, sv.frame.origin.y + tableExtHeight, sv.frame.size.width, sv.frame.size.height);
}
}
}
- (void)show{
[self prepare];
[super show];
}
- (void)prepare {
if (tableHeight == 0) {
tableHeight = 150.0f;
}
kTablePadding = 8.0f;
tableExtHeight = tableHeight + 2 * kTablePadding;
[self setNeedsLayout];
}
#end
/*the UIAlertTableView class is imported into the myViewController header file*/
/*myViewController.m*/
#implementation myViewController
#synthesize myTableView;
#synthesize alert;
#synthesize imageView;
#synthesize scrollView;
#synthesize models;
#synthesize picked;
#pragma myTableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [models count];
}
- (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];
}
// now configure the cell
cell.textLabel.text = [models objectAtIndex:[indexPath row]];
[cell setAccessibilityTraits: UIAccessibilityTraitButton];
return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (returnedSetting && (indexPath.row == prevSelectedIndex)){
returnedSetting = FALSE;
}
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
//index path to row that's selected
NSIndexPath *myIndexPath = [myTableView indexPathForSelectedRow];
UITableViewCell *cell = [myTableView cellForRowAtIndexPath:myIndexPath];
labelText = cell.textLabel.text;
selectedModel = cell.textLabel.text;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSIndexPath *myIndexPath = [tableView indexPathForSelectedRow];
prevSelectedIndex = myIndexPath.row;
UITableViewCell *cell = [tableView cellForRowAtIndexPath:myIndexPath];
[alert dismissWithClickedButtonIndex:0 animated:YES];
labelText = cell.textLabel.text;
selectedModel = cell.textLabel.text;
[self dismissModalViewControllerAnimated:YES];
}
-(void)removeButton{
[UIView animateWithDuration:1.5
delay:1.5
options:UIViewAnimationCurveEaseInOut
animations:^ {
eButton.alpha = 0;
}
completion:^(BOOL finished) {
}];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
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.
}
-(void)showAlertFor:(NSTimer *)timer{
[alert show];
myTableView.frame = CGRectMake(11.0f, alert.lowestView.frame.origin.y + alert.lowestView.frame.size.height + 2 * alert.kTablePadding, alert.tableWidth, alert.tableHeight);
[alert insertSubview:myTableView atIndex:1];
[myTableView performSelector:#selector(flashScrollIndicators) withObject:nil afterDelay:.3];
}
-(void)bringupAlertTableViewFor:(NSString *)dName atLocationOnScreen:(CGPoint)newPoint{
if (([dName isEqualToString:#"hello"]){
picked =TRUE;
myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, 0.0f) style:UITableViewStylePlain];
alert = [[UIAlertTableView alloc] initWithTitle:dName
message:#"Choose from the table below:"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:nil];
[alert setDelegate: alert.alertDelegate];
models = [[NSMutableArray alloc]init];
myTableView.delegate = self;
myTableView.dataSource = self;
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:#"Decisions" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"dName == %#", dName];
[request setPredicate: predicate];
NSError *error;
//matches found
NSArray *matchingData = [context executeFetchRequest: request error: &error];
for (NSManagedObject *obj in matchingData) {
[models addObject:[NSString stringWithFormat:#"%#",[obj valueForKey: #"model"]]];
}
alert.tableHeight = 120;
[alert show];
myTableView.frame = CGRectMake(11.0f, alert.lowestView.frame.origin.y + alert.lowestView.frame.size.height + 2 * alert.kTablePadding, alert.tableWidth, alert.tableHeight);
[alert insertSubview:myTableView atIndex:1];
[myTableView performSelector:#selector(flashScrollIndicators) withObject:nil afterDelay:.3];
}else{
picked = TRUE;
frame.origin.x = newPoint.x - 29; // new x coordinate
frame.origin.y = 240; // new y coordinate
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration: 1.5];
[UIView commitAnimations];
myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.0f, 0.0f) style:UITableViewStylePlain];
alert = [[UIAlertTableView alloc] initWithTitle:dName
message:#"Select a choice:"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:nil];
[alert setDelegate: alert.alertDelegate];
models = [[NSMutableArray alloc]init];
myTableView.delegate = self;
myTableView.dataSource = self;
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:#"Decisions" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"deName == %#", dName];
[request setPredicate: predicate];
NSError *error;
//matches found
NSArray *matchingData = [context executeFetchRequest: request error: &error];
for (NSManagedObject *obj in matchingData) {
[models addObject:[NSString stringWithFormat:#"%#",[obj valueForKey: #"model"]]];
}
alert.tableHeight = 120;
[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:#selector(showAlertFor:) userInfo:nil repeats:NO];
previousPoint = newPoint;
}
}
-(IBAction)singleTapImageView:(UITapGestureRecognizer *)sender {
CGPoint pt = [sender locationInView: sender.view];
//find out which was pressed
if ( ((pt.x >= 52) && (pt.x <= 79)) && ((pt.y >= 269) && (pt.y <= 296))){
CGPoint newPoint = {45, (257 + 55)};
[self bringupAlertTableViewFor:#"Choice1" atLocationOnScreen:newPoint];
}
}
#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)sView{
[self removeButton];
}
-(void)scrollViewDidScroll:(UIScrollView *)sView{
eButton.alpha = .7;
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)sView
{
[self removeButton];
}
-(void)exitButtonPressed{
[self dismissModalViewControllerAnimated:YES];
}
- (void)viewDidLoad
{
UIImage *imageS = [UIImage imageNamed:#"ti.png"];
imageView = [[TouchDetectingImageView alloc]initWithImage:imageS];
[imageView setDelegate:self];
imageView.frame = CGRectMake(20, 25, imageS.size.width,imageS.size.height);
CGFloat newScrollWidth = imageView.image.size.width + 20;
[scrollView setContentSize:(CGSizeMake(newScrollWidth, imageView.image.size.height))];
[scrollView addSubview: imageView];
imageView.contentMode = UIViewContentModeScaleToFill;
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(singleTapImageView:)];
singleTap.numberOfTapsRequired = 1;
[scrollView addGestureRecognizer:singleTap];
UIImage *img = [UIImage imageNamed:#"backbutton.png"];
CGRect frameForButton = CGRectMake(0, 3, img.size.width, img.size.height);
eButton = [[exitButton alloc] initWithFrame:frameForButton];
[eButton setDelegate:self];
[eButton addTarget:self action:#selector(exitButtonPressed) forControlEvents:UIControlEventTouchUpInside];
UITapGestureRecognizer *buttonTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(exitButtonPressed)];
buttonTap.numberOfTapsRequired = 1;
[eButton addGestureRecognizer:buttonTap];
eButton.alpha = 0;
[self.view addSubview:eButton];
[super viewDidLoad];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewDidUnload
{
[self setScrollView:nil];
[self setImageView:nil];
[self setmyTableView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
[scrollView flashScrollIndicators];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// The menu is only going to support landscape orientations
return ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight));
}
- (NSInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight;
}
-(BOOL)shouldAutorotate{
return YES;
}
#end
The reason(s) for this were:
1) the call to layoutAnimated was being ignored
2) it appears that ios 6 handles view hierarchy somewhat differently...
3) ios 6.0 automatically scales to fit a 1136x640 display vs earlier version that scale to fit a 960x640 display.
solutions were:
use a layoutsubviews call and layoutifneeded
also using conditional statements to find the ios version (e.g. greater_than_or_equal_to ios 6.0)

Picker View does not reappear once dismissed, and text field clicked a second time

Here's a simplified code, with a view controller with just a text field I also updated the title to reflect the newer issue.
When run, I click the text field and it brings up the picker view, and I'm able to click a value on the picker view and it shows up on the text field. I'm able to dismiss the picker view now when I press the Done button on the navigation bar. But now when I click the text field a second time, I don't get the picker view to pop up a second time.
import
#interface MyPickerViewViewController : UIViewController <UIPickerViewDelegate,
UIPickerViewDataSource,
UITextFieldDelegate>
#end
#interface MyPickerViewViewController () {
UIPickerView *_pv;
NSArray *_array;
IBOutlet __weak UITextField *_tf;
}
#end
#implementation MyPickerViewViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_array = [NSArray arrayWithObjects:#"One", #"Two", #"Three", nil];
// Do any additional setup after loading the view, typically from a nib.
_pv = [[UIPickerView alloc] initWithFrame:CGRectZero];
_pv.dataSource = self;
_pv.delegate = self;
_tf.inputView = _pv;
UIToolbar* mypickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 56)];
mypickerToolbar.barStyle = UIBarStyleBlackOpaque;
[mypickerToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(pickerDoneClicked:)];
[barItems addObject:doneBtn];
[mypickerToolbar setItems:barItems animated:YES];
_tf.inputAccessoryView = mypickerToolbar;
_tf.delegate = self;
}
- (void)pickerDoneClicked:(id)sender
{
[_pv removeFromSuperview];
[_tf.inputView removeFromSuperview];
[_tf.inputAccessoryView removeFromSuperview];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// Added this method and now the picker view comes up every time I
// click on the text field, even after I dismiss it. However, the
// picker view is in wrong place, so I just have to adjust the
// CGRect assigned to it.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
[self.view addSubview:_tf.inputAccessoryView];
[self.view addSubview:_tf.inputView];
return NO;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
NSLog(#"Hello there");
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
[textField resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated
{
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:( NSInteger)component
{
return [_array objectAtIndex:row];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return _array.count;
}
- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
_tf.text = [_array objectAtIndex:row];
}
#end
I think you missed this:
[datePicker removeFromSuperview];
[pickerView removeFromSuperview];
You may try:
[self.view endEditing:YES];
in your action method
See update with this addition
// Added this method and now the picker view comes up every time I
// click on the text field, even after I dismiss it. However, the
// picker view is in wrong place, so I just have to adjust the
// CGRect assigned to it.
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
[self.view addSubview:_tf.inputAccessoryView];
[self.view addSubview:_tf.inputView];
return NO;
}
Here is an adjusted CGRect for the pickerview and tool bar that worked. I was wondering though if there is a default height for a pickerview?
- (void)viewDidLoad
{
[super viewDidLoad];
_array = [NSArray arrayWithObjects:#"One", #"Two", #"Three", #"Four", nil];
// Do any additional setup after loading the view, typically from a nib.
CGRect viewRect = [[UIScreen mainScreen] bounds];
CGFloat pvHeight = 235;
CGFloat pvYpos = viewRect.size.height - pvHeight;
CGRect pvRect = CGRectMake(viewRect.origin.x, pvYpos, viewRect.size.width, pvHeight);
_pv = [[UIPickerView alloc] initWithFrame:pvRect];
_pv.dataSource = self;
_pv.delegate = self;
_tf.inputView = _pv;
CGFloat tbYpos = pvYpos-44;
UIToolbar* mypickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, tbYpos, viewRect.size.width, 44)];
mypickerToolbar.barStyle = UIBarStyleBlackOpaque;
[mypickerToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(pickerDoneClicked:)];
[barItems addObject:doneBtn];
[mypickerToolbar setItems:barItems animated:YES];
_tf.inputAccessoryView = mypickerToolbar;
_tf.delegate = self;
}

UInavigationbar and super dealloc causing app crash

I am having a application crash when i use back button in UINavigation child and child [supper dealloc] called application get crash. I tried but i am not able to find any error. Instrument saying below issue but i am not getting the point here
# Address Category Event Type RefCt Timestamp Size Responsible Library Responsible Caller
0 0x9e8c8c0 CALayer Malloc 1 00:05.082.180 48 UIKit -[UIView _createLayerWithFrame:]
1 0x9e8c8c0 CALayer Zombie -1 00:18.855.037 0 QuartzCore CA::release_objects(X::List<void const*>*)
if you can help me i will be great thankfull to you.
Here is the root page code
//
// TNTScenarioViewController.m
// TurfNutritionTool
//
// Created by Aashish Joshi on 10/20/11.
// Copyright 2011 Abacus Consultancy Services. All rights reserved.
//
#import "TNTScenarioViewController.h"
#import "ScenarioDetailViewController.h"
#import <QuartzCore/QuartzCore.h>
#implementation TNTScenarioViewController
#synthesize scenarioTable = _scenarioTable;
#synthesize scenarioDetail = _scenarioDetail;
#synthesize scenarioId = _scenarioId;
#synthesize scenarioTableCellStyle = _scenarioTableCellStyle;
#synthesize dbObject = _dbObject;
#synthesize headerDateLabel = _headerDateLabel;
#synthesize headerTurfAcresLabel = _headerTurfAcresLabel;
#synthesize headerScenarioIDLabel = _headerScenarioIDLabel;
#synthesize headerDescriptionLabel = _headerDescriptionLabel;
#synthesize headerProductTypeLabel = _headerProductTypeLabel;
#synthesize headerTargetNitrogenLabel = _headerTargetNitrogenLabel;
#synthesize headerView = _headerView;
#synthesize synchronize = _synchronize;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
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
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
UIColor *_background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"main_login_bg.png"]];
self.view.backgroundColor = _background;
[_background release];
_scenarioTable.delegate = self;
_scenarioTable.dataSource = self;
// Set the table view to be rounded
[[self.scenarioTable layer] setCornerRadius:5.0];
[self loadDBAccessDatabase];
// [self didApplicationLaunchedFirstTime];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIToolbar* _rightNavBarTools = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 260, 44)];
// create the array to hold the buttons, which then gets added to the toolbar
NSMutableArray* _rightNavBarButtons = [[NSMutableArray alloc] initWithCapacity:4];
UIBarButtonItem *_signout = [[UIBarButtonItem alloc] initWithTitle:#"Sign out" style:UIBarButtonItemStyleBordered target:self action:#selector(didApplicationLaunchedFirstTime)];
[_rightNavBarButtons addObject:_signout];
[_signout release];
UIBarButtonItem *_syncronize = [[UIBarButtonItem alloc] initWithTitle:#"Synchronize" style:UIBarButtonItemStyleBordered target:self action:#selector(syncronize)];
[_rightNavBarButtons addObject:_syncronize];
[_syncronize release];
UIBarButtonItem *_addNewScenario = [[UIBarButtonItem alloc]
initWithTitle:#"New TNT" style:UIBarButtonItemStyleBordered target:self
action:#selector(startNewScenario)];
[_rightNavBarButtons addObject:_addNewScenario];
[_addNewScenario release];
[_rightNavBarTools setItems:_rightNavBarButtons animated:NO];
[_rightNavBarButtons release];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:_rightNavBarTools] autorelease];
[_rightNavBarTools release];
[self loadAllScenario];
}
- (void)viewWillAppear:(BOOL)animated
{
NSLog(#"%d", [self retainCount]);
[super viewWillAppear:animated];
[self loadAllScenario];
[self.scenarioTable reloadData];
}
- (void)viewDidUnload
{
[_scenarioTable release];
[_scenarioDetail release];
[_scenarioId release];
[_scenarioTableCellStyle release];
self.scenarioTable = nil;
self.scenarioDetail = nil;
self.scenarioId = nil;
self.scenarioTableCellStyle = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return [self.scenarioId count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"scenarioTableCellStyle" owner:self options:nil];
cell = self.scenarioTableCellStyle;
self.scenarioTableCellStyle = nil;
}
if (indexPath.row % 2 == 0) {
cell.contentView.backgroundColor = [UIColor colorWithWhite:253.0/255 alpha:1];
} else {
cell.contentView.backgroundColor = [UIColor colorWithWhite:250.0/255 alpha:1];
}
NSDictionary * _scenarioDetailRow = [self.dbObject getScenarioDetail:[self.scenarioId objectAtIndex:indexPath.row]];
NSNumber* _tempNumber;
NSNumberFormatter* _formatter = [[NSNumberFormatter alloc] init];
NSString* _convertedNumber;
// Configure the cell...
_tempNumber = [_scenarioDetailRow objectForKey:#"scenarioid"];
[_formatter setNumberStyle:NSNumberFormatterDecimalStyle];
_convertedNumber = [_formatter stringForObjectValue:_tempNumber];
UILabel* _label = (UILabel *)[cell viewWithTag:1];
_label.text = _convertedNumber;
_label = (UILabel *)[cell viewWithTag:2];
NSString* _turftype = [_scenarioDetailRow objectForKey:#"turf"];
_label.text = _turftype;
_label = (UILabel *)[cell viewWithTag:3];
_tempNumber = [_scenarioDetailRow objectForKey:#"targetnitrogen"];
[_formatter setNumberStyle:NSNumberFormatterDecimalStyle];
_convertedNumber = [_formatter stringForObjectValue:_tempNumber];
_label.text = _convertedNumber;
_label = (UILabel *)[cell viewWithTag:4];
_tempNumber = [_scenarioDetailRow objectForKey:#"turfacre"];
[_formatter setNumberStyle:NSNumberFormatterDecimalStyle];
_convertedNumber = [_formatter stringForObjectValue:_tempNumber];
_label.text = _convertedNumber;
[_formatter release];
_label = (UILabel *)[cell viewWithTag:5];
NSString* _dateCreated = [_scenarioDetailRow objectForKey:#"datecreated"];
NSDateFormatter *inputFormatter = [[[NSDateFormatter alloc] init] autorelease];
[inputFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *_inputDateCreated = [inputFormatter dateFromString:_dateCreated];
NSDateFormatter *outputFormatter = [[[NSDateFormatter alloc] init] autorelease];
[outputFormatter setDateFormat:#"MM-dd-yyyy"];
NSString *_outputDateCreated = [outputFormatter stringFromDate:_inputDateCreated];
_label.text = _outputDateCreated;
_label = (UILabel *)[cell viewWithTag:6];
if (([_scenarioDetailRow objectForKey:#"description"] != nil) && ([_scenarioDetailRow objectForKey:#"description"] != (id)[NSNull null])){
NSString* _discription = [_scenarioDetailRow objectForKey:#"description"];
_label.text = _discription;
} else {
_label.text = [NSString stringWithString:#""];
}
return cell;
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
if (UIInterfaceOrientationIsLandscape(fromInterfaceOrientation))
{
// Move the plots into place for portrait
_headerScenarioIDLabel.frame = CGRectMake(-30, 2, 125, 20);
_headerDescriptionLabel.frame = CGRectMake(52, 2, 125, 20);
_headerProductTypeLabel.frame = CGRectMake(278, 2, 125, 20);
_headerTargetNitrogenLabel.frame = CGRectMake(368, 2, 125, 20);
_headerTurfAcresLabel.frame = CGRectMake(437, 2, 125, 20);
_headerDateLabel.frame = CGRectMake(545, 2, 125, 20);
}
else
{
// Move the plots into place for landscape
_headerScenarioIDLabel.frame = CGRectMake(-26, 2, 125, 20);
_headerDescriptionLabel.frame = CGRectMake(85, 2, 125, 20);
_headerProductTypeLabel.frame = CGRectMake(390, 2, 125, 20);
_headerTargetNitrogenLabel.frame = CGRectMake(526, 2, 125, 20);
_headerTurfAcresLabel.frame = CGRectMake(626, 2, 125, 20);
_headerDateLabel.frame = CGRectMake(759, 2, 125, 20);
}
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
_headerScenarioIDLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
_headerDateLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
_headerDescriptionLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
_headerProductTypeLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
_headerTargetNitrogenLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
_headerTurfAcresLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
BOOL isLandscape = UIDeviceOrientationIsLandscape(self.interfaceOrientation);
if (UIInterfaceOrientationIsLandscape(orientation) || isLandscape)
{
// Move the plots into place for landscape
_headerScenarioIDLabel.frame = CGRectMake(-26, 2, 125, 20);
_headerDescriptionLabel.frame = CGRectMake(85, 2, 125, 20);
_headerProductTypeLabel.frame = CGRectMake(390, 2, 125, 20);
_headerTargetNitrogenLabel.frame = CGRectMake(526, 2, 125, 20);
_headerTurfAcresLabel.frame = CGRectMake(626, 2, 125, 20);
_headerDateLabel.frame = CGRectMake(759, 2, 125, 20);
}
else
{
// Move the plots into place for portrait
_headerScenarioIDLabel.frame = CGRectMake(-30, 2, 125, 20);
_headerDescriptionLabel.frame = CGRectMake(52, 2, 125, 20);
_headerProductTypeLabel.frame = CGRectMake(278, 2, 125, 20);
_headerTargetNitrogenLabel.frame = CGRectMake(368, 2, 125, 20);
_headerTurfAcresLabel.frame = CGRectMake(437, 2, 125, 20);
_headerDateLabel.frame = CGRectMake(545, 2, 125, 20);
}
if(_headerView == nil) {
//allocate the view if it doesn't exist yet
_headerView = [[UIView alloc] init];
UIColor *_background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"toolbar_bkg.png"]];
_headerView.backgroundColor = _background;
[_background release];
_headerScenarioIDLabel.backgroundColor = [UIColor clearColor];
_headerScenarioIDLabel.opaque = NO;
_headerScenarioIDLabel.textColor = [UIColor whiteColor];
_headerScenarioIDLabel.font = [UIFont boldSystemFontOfSize:12];
_headerScenarioIDLabel.textAlignment = UITextAlignmentCenter;
_headerScenarioIDLabel.text = #"ID";
_headerDateLabel.backgroundColor = [UIColor clearColor];
_headerDateLabel.opaque = NO;
_headerDateLabel.textColor = [UIColor whiteColor];
_headerDateLabel.font = [UIFont boldSystemFontOfSize:12];
_headerDateLabel.textAlignment = UITextAlignmentCenter;
_headerDateLabel.text = #"Date";
_headerDescriptionLabel.backgroundColor = [UIColor clearColor];
_headerDescriptionLabel.opaque = NO;
_headerDescriptionLabel.textColor = [UIColor whiteColor];
_headerDescriptionLabel.font = [UIFont boldSystemFontOfSize:12];
_headerDescriptionLabel.textAlignment = UITextAlignmentCenter;
_headerDescriptionLabel.text = #"Description";
_headerProductTypeLabel.backgroundColor = [UIColor clearColor];
_headerProductTypeLabel.opaque = NO;
_headerProductTypeLabel.textColor = [UIColor whiteColor];
_headerProductTypeLabel.font = [UIFont boldSystemFontOfSize:12];
_headerProductTypeLabel.textAlignment = UITextAlignmentCenter;
_headerProductTypeLabel.text = #"Product Type";
_headerTargetNitrogenLabel.backgroundColor = [UIColor clearColor];
_headerTargetNitrogenLabel.opaque = NO;
_headerTargetNitrogenLabel.textColor = [UIColor whiteColor];
_headerTargetNitrogenLabel.font = [UIFont boldSystemFontOfSize:12];
_headerTargetNitrogenLabel.textAlignment = UITextAlignmentCenter;
_headerTargetNitrogenLabel.text = #"Target N";
_headerTurfAcresLabel.backgroundColor = [UIColor clearColor];
_headerTurfAcresLabel.opaque = NO;
_headerTurfAcresLabel.textColor = [UIColor whiteColor];
_headerTurfAcresLabel.font = [UIFont boldSystemFontOfSize:12];
_headerTurfAcresLabel.textAlignment = UITextAlignmentCenter;
_headerTurfAcresLabel.text = #"Turf Acres";
//add the button to the view
[_headerView addSubview:_headerScenarioIDLabel];
[_headerView addSubview:_headerDescriptionLabel];
[_headerView addSubview:_headerProductTypeLabel];
[_headerView addSubview:_headerTargetNitrogenLabel];
[_headerView addSubview:_headerTurfAcresLabel];
[_headerView addSubview:_headerDateLabel];
}
//return the view for the footer
return _headerView;
}
// specify the height of your footer section
- (CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section {
//differ between your sections or if you
//have only on section return a static value
return 24;
}
- (CGFloat)tableView:(UITableView *)tableView
heightForFooterInSection:(NSInteger)section {
//differ between your sections or if you
//have only on section return a static value
return 14;
}
- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
UIColor *_background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"toolbar_bkg.png"]];
UIView* _customView = [[[UIView alloc]initWithFrame:CGRectMake(10.0, 0.0, 300.0, 44.0)]autorelease];
_customView.backgroundColor = _background;
[_background release];
return _customView;
}
/*
// 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:[NSArray arrayWithObject: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.
ScenarioDetailViewController* _detailViewController = [[ScenarioDetailViewController alloc] initWithNibName:#"ScenarioDetailViewController" bundle:nil];
_detailViewController.dbObject = self.dbObject;
[_detailViewController setScenarioId:[self.scenarioId objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:_detailViewController animated:YES];
[_detailViewController release];
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
// Updates the appearance of the Edit|Done button as necessary.
[super setEditing:editing animated:animated];
[self.scenarioTable setEditing:editing animated:YES];
// Disable the add button while editing.
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// must update the database before updating the tableView
// so that the tableView never has a row that's missing from the database
[self.dbObject deleteScenarioRow:[self.scenarioId objectAtIndex:indexPath.row]];
[self loadAllScenario];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[self.scenarioTable reloadData];
}
}
- (void)dealloc {
[_synchronize release];
[_scenarioTable release];
[_scenarioDetail release];
[_scenarioId release];
[_scenarioTableCellStyle release];
[_headerDateLabel release];
[_headerTurfAcresLabel release];
[_headerScenarioIDLabel release];
[_headerDescriptionLabel release];
[_headerProductTypeLabel release];
[_headerTargetNitrogenLabel release];
[_headerView release];
[super dealloc];
}
// Called when an alertview button is touched
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
switch (buttonIndex) {
case 0:
{
NSLog(#"user not want to sync");
}
break;
case 1:
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
_synchronize = [[TNSynchronize alloc] init];
_synchronize.delegate = self;
[_synchronize jesonRequest];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
break;
}
}
- (void) reloadAfterSyncronize {
[self loadAllScenario];
[self.scenarioTable reloadData];
}
#pragma mark - TNTScenarioViewController lifecycle methods
- (void) syncronize {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Syncronize process", nil)
message:NSLocalizedString(#"\n Syncronize process will be start and work in background.", nil)
delegate:self
cancelButtonTitle:NSLocalizedString(#"Cancel", nil)
otherButtonTitles:NSLocalizedString(#"Ok", nil), nil];
[alert show];
[alert release];
}
- (void) didApplicationLaunchedFirstTime {
LoginViewController *loginViewObj = [[[LoginViewController alloc] init] autorelease];
loginViewObj.dbObject = self.dbObject;
UINavigationController *navigationController = [[[UINavigationController alloc]
initWithRootViewController:loginViewObj] autorelease];
navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentModalViewController:navigationController animated:YES];
}
- (void)loadSynchronizeController {
[self.scenarioTable reloadData];
}
// This is Method to New Scenario
- (void) startNewScenario {
ScenarioDetailViewController* _detailViewController = [[ScenarioDetailViewController alloc] initWithNibName:#"ScenarioDetailViewController" bundle:nil];
[_detailViewController setScenarioId:[NSNumber numberWithInt:0]];
[self.navigationController pushViewController:_detailViewController animated:YES];
// [_detailViewController release];
}
// This Method use for Load Value of Scenario
- (NSMutableArray *) loadAllScenario {
// NSLog(#"%s", __FUNCTION__);
// First, test for existence.
NSArray* _paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* _documentsDirectory = [_paths objectAtIndex:0];
NSString* _writableConfigPath = [_documentsDirectory stringByAppendingPathComponent:#"Configuration.plist"];
NSMutableDictionary* _configFile = [[NSMutableDictionary alloc] initWithContentsOfFile:_writableConfigPath];
NSString* _loginStatus= [NSString stringWithString:[_configFile objectForKey:#"UserEmail"]];
[_configFile autorelease];
[self.scenarioId removeAllObjects];
if (!_dbObject) [self loadDBAccessDatabase];
self.scenarioId = [NSMutableArray arrayWithArray:[_dbObject getRelatedScenarioArray:_loginStatus]];
return self.scenarioId;
}
- (NSArray *) loadScenarioIDsIfEmpty {
// NSLog(#"%s", __FUNCTION__);
// First, test for existence.
NSArray* _paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* _documentsDirectory = [_paths objectAtIndex:0];
NSString* _writableConfigPath = [_documentsDirectory stringByAppendingPathComponent:#"Configuration.plist"];
NSMutableDictionary* _configFile = [[NSMutableDictionary alloc] initWithContentsOfFile:_writableConfigPath];
NSString* _loginStatus = [NSString stringWithString:[_configFile objectForKey:#"UserEmail"]];
[_configFile autorelease];
if (!_dbObject) [self loadDBAccessDatabase];
if (!self.scenarioId || ![self.scenarioId count]) self.scenarioId = [NSMutableArray arrayWithArray:[_dbObject getRelatedScenarioArray:_loginStatus]];
return self.scenarioId;
}
- (DBAccess *) loadDBAccessDatabase {
// NSLog(#"%s", __FUNCTION__);
_dbObject = [DBAccess sharedDBObjectAccess];
return _dbObject;
}
#end
This is the dealloc method as you asked
- (void)dealloc {
[_scenarioProductTable release];
[_attributePopover release];
[_gotMapRegion release];
[_gotTargetN release];
[_gotTurfAcres release];
[_gotTurftype release];
[_scenarioId release];
[_granularProductData release];
[_liquidProductData release];
[_areaGraphData release];
[_scenarioAppId release];
[_scenarioProductTableCellStyle release];
[_scenarioProductTable release];
[_carryOver release];
[_tempDiscription release];
[_scenarioDetailRow release];
[_turfacresTextField release];
[_discriptionTextField release];
[_footerView release];
[_headerView release];
[selectedTurftypeLabel release];
[selectedTargetNLabel release];
[selectedMapregionLabel release];
[selectedTurfAcresLabel release];
[_loginUser release];
[super dealloc];
}
and in this function it saying that i have the issue
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
ScenarioDetailViewController* _detailViewController = [[ScenarioDetailViewController alloc] initWithNibName:#"ScenarioDetailViewController" bundle:nil];
_detailViewController.dbObject = self.dbObject;
[_detailViewController setScenarioId:[self.scenarioId objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:_detailViewController animated:YES];
[_detailViewController release];
}
and this line have 100% blame in the funnction
[self.navigationController pushViewController:_detailViewController animated:YES];
From the crash report, it is apparent that you are overreleasing an object (notice where it says the zombie CALayer has a retain count of -1; anything less than 0 is overreleased). My suggestion is either scour your code until you find it, use the Instruments tool 'Zombies' (which only works when profiling on the Simulator), or upgrade your project to ARC.
I would definitely recommend upgrading to ARC as the best choice. ARC streamlines your code and lowers your peak memory footprint, improving efficiency and greatly reducing the chances of a crash.
Edit:
To upgrade to ARC: (from the Xcode menu)
Edit -> Refactor -> Convert to Objective-C ARC...
(from Apple's Face Detection example project)
Edit 2:
In response to #Chris's answer:
In viewDidUnload you should only release objects that are created in viewDidLoad; also, you should usually only be setting IBOutlets to nil. For every time viewDidUnload is called, viewDidLoad will be called to recreate everything that was destroyed in viewDidUnload. So the lesson is in viewDidUnload, only nil out objects that are created in viewDidLoad. If you release something that isn't created in viewDidLoad, it won't be recreated when you return to that view, which can cause a crash.
Yet I don't think that is your problem here. viewDidUnload is not actually called when a view controller is destroyed (dealloc is called because the controller was popped from the navigation stack or the modal view controller was dismissed). viewDidUnload is only called when the application receives a memory warning- viewDidUnload's job is to release any objects that can be recreated later. Assuming you don't receive any memory warnings and you are just pushing/popping a view controller from the stack, the double release is viewDidUnload is not causing this problem (though it might cause one later).
Moral of the story:
Use ARC. It's not a toy, it really works. It won't 'lessen' your control over memory management- it removes the need for it. Apart from retain cycles (Brad Larson gives a nice explanation here: What kind of leaks does automatic reference counting in Objective-C not prevent or minimize?), ARC will take care of just about all of your memory management, especially leaks. You can still get rid of an object with:
someObject = nil;
so you can still control your memory footprint. #autoreleasepools are also still an option with ARC.
So, final moral of the story:
Use ARC.
- (void)viewDidUnload
{
[_scenarioTable release];
[_scenarioDetail release];
[_scenarioId release];
[_scenarioTableCellStyle release];
self.scenarioTable = nil;
self.scenarioDetail = nil;
self.scenarioId = nil;
self.scenarioTableCellStyle = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
Your -viewDidUnload method is double-releasing. First you explicitly release objects by referencing their instance variables, ie: [_scenarioTable release];. But you don't set the ivar to nil after doing that. So those instance variables still point to released objects.
Then you set the properties which are backed by those instance variables to nil. The properties are probably declared as using the retain memory management strategy. This means when you do self.scenarioTable = nil;, it will release the ivar associated with the property.
To fix this, just get rid of the 4 release calls at the top.
- (void)viewDidUnload
{
self.scenarioTable = nil;
self.scenarioDetail = nil;
self.scenarioId = nil;
self.scenarioTableCellStyle = nil;
[super viewDidUnload];
}
If you really want to keep those, change it to this:
- (void)viewDidUnload
{
[_scenarioTable release]; _scenarioTable = nil;
[_scenarioDetail release]; _scenarioDetail = nil;
[_scenarioId release]; _scenarioId = nil;
[_scenarioTableCellStyle release]; _scenarioTableCellStyle = nil;
[super viewDidUnload];
}
And this is why -viewDidUnload is deprecated in iOS 6.
like Rickay said, in your dealloc method and your viewDidUnload you release your 4 scenario objects twice. I've only used ARC but I'm pretty sure thats your issue

Add custom UIButton to UIKeyboard's accessory view for a UIWebView

I need to add a camera button to a UIWebView's keyboard accessory view toolbar (the one that already has the "Back|Next" and "Done" buttons).
Is there an easy way to do this?
I'm still looking for a better way to do it, but one solution for the moment would be to destroy the bar and recreate it like so :
- (void)viewDidLoad
{
[super viewDidLoad];
UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
NSURL *aURL = [NSURL URLWithString:#"http://www.google.com"];
NSURLRequest *aRequest = [NSURLRequest requestWithURL:aURL];
[web loadRequest:aRequest];
[self.view addSubview:web];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}
- (void)keyboardWillShow:(NSNotification *)notification {
[self performSelector:#selector(removeBar) withObject:nil afterDelay:0];
}
- (void)removeBar {
UIWindow *keyboardWindow = nil;
for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {
if (![[testWindow class] isEqual:[UIWindow class]]) {
keyboardWindow = testWindow;
break;
}
}
for (UIView *possibleFormView in [keyboardWindow subviews]) {
// iOS 5 sticks the UIWebFormView inside a UIPeripheralHostView.
if ([[possibleFormView description] rangeOfString:#"UIPeripheralHostView"].location != NSNotFound) {
for (UIView *subviewWhichIsPossibleFormView in [possibleFormView subviews]) {
if ([[subviewWhichIsPossibleFormView description] rangeOfString:#"UIWebFormAccessory"].location != NSNotFound) {
UISegmentedControl *nav = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:#"Previous",#"Next", nil]];
nav.momentary = YES;
nav.frame = CGRectMake(5, 8, 120, 30);
nav.segmentedControlStyle = UISegmentedControlStyleBar;
nav.tintColor = [UIColor colorWithWhite:0.25 alpha:1];
[nav addTarget:self action:#selector(navigate) forControlEvents:UIControlEventValueChanged];
UIBarButtonItem *pictureBtn =[[UIBarButtonItem alloc] initWithTitle:#"Picture" style:UIBarButtonItemStyleBordered target:self action:#selector(takePic:)];
UIBarButtonItem *flexButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *doneButton =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(resignKeyboard)];
NSArray *buttons = [NSArray arrayWithObjects:flexButton,pictureBtn,flexButton,doneButton, nil];
[(UIToolbar *)subviewWhichIsPossibleFormView addSubview:nav];
[(UIToolbar *)subviewWhichIsPossibleFormView setItems:buttons];
}
}
}
}
}
But then, you have to implement the previous, next and done function again. But it's not the hardest part.
there is an easier way to do this.
Keep your keyboard notification in your viewDidLoad
After that all you will need is the following method:
-(void)keyboardDidShow:(NSNotification*)notif
{
NSArray *array = [[UIApplication sharedApplication] windows];
for (UIWindow* wind in array) {
for (UIView* currView in wind.subviews) {
if ([[currView description] hasPrefix:#"<UIPeripheralHostView"]) {
for (UIView* perView in currView.subviews) {
if ([[perView description] hasPrefix:#"<UIWebFormAccessory"]) {
UIBarButtonItem *doneBttn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(resignKeyBoard)];
NSMutableArray *arr = [[NSMutableArray alloc] initWithArray: [(UIToolbar *) perView items]];
[arr addObject:doneBttn];
[(UIToolbar *) perView setItems:arr];
}
}
}
}
}
}
I have basically taken the original prev/next buttons from the UIWebFormAccessory and added a done button to the end of it, but you can add what ever buttons you want to this.
Some may think this shouldn't be implemented in -(void)keyboardDidShow: because you are changing the UI after it displays on screen, but so far I haven't noticed any issues with this. (only tested in simulator)
Hope this was useful!