Xcode How to stop a timer Label with an if statement when a UITextField has the same text as a UILabel - xcode

I have been trying to do this on an app for a long time but I cannot get it to work, please could someone help me and post some code on how I would do it. What I need to happen is when the text in the UITextField equal the UILabel. Thanks
h. viewcontroller
#interface AlphabetSceneViewController : UIViewController {
UILabel *stopWatchLabel;
NSTimer *stopWatchTimer;
NSDate *startDate;
IBOutlet UILabel *wordToType;
IBOutlet UITextField *wordTyped;
and the m. view controller
- (void)updateTimer
{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"mm:ss.SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
stopWatchLabel.text = timeString;
}
- (IBAction)onStartPressed:(id)sender {
startDate = [NSDate date];
stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:#selector(updateTimer)
userInfo:nil
repeats:YES];
}
- (IBAction)onStopPressed:(id)sender {
[stopWatchTimer invalidate];
stopWatchTimer = nil;
[self updateTimer];
if ([wordToType.text isEqualToString:#"stop"]) {
}
}
Help much appreciated!

I figured out how to do it, I'll put up the code for anyone that wanted to know. It's only code for the .m file and the alert view is just a bit of extra code on the end to make it show an alert when with the time that the user had when the timer stops.
- (IBAction)stopTimer:(id)sender {
if([wordTyped.text isEqualToString:wordToType.text]){
[stopWatchTimer invalidate];
stopWatchTimer = nil;
[self updateTimer];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Nice Work" message:[NSString stringWithFormat:#"Good Job! You're time to type the alphabet was %#. Let's see if you can do better...", stopWatchLabel.text]
delegate:self cancelButtonTitle:#"Main Menu" otherButtonTitles: nil];
[alert show];
}
}

Related

Disable a particular date in UIDatePicker

I was trying to set up a uidatepicker for booking some events in the calendar.
I need to disable (hide) some particular dates in my UIDatePicker, for instance days when I'm out of town or on vacation.
Can you help me with this one?
Thanx a lot in advance.
Here is some code:
- (void)viewDidLoad
{
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"IT"];
[self.datePicker setLocale:locale];
NSString *min = #"20132015";
NSString *max = #"22132015";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"ddMMyyyy HH:mm"];
NSDate *datemin = [dateFormat dateFromString:min];
NSDate *datemax = [dateFormat dateFromString:max];
[self.view addSubview:datePicker];
datePicker.minuteInterval = 15;
datePicker.maximumDate = datemax;
datePicker.minimumDate = [NSDate date];
[datePicker addTarget:self action:#selector(disableDate) forControlEvents:UIControlEventValueChanged];
[datePicker addTarget:self
action:#selector(LabelChange:)
forControlEvents:UIControlEventValueChanged];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
-(void)disableDate{
NSDate *pickedDate = datePicker.date; // Get current Date
NSDate *disabledDate = [?????;
if([pickedDate compare:disabledDate] == NSOrderedSame)
{
[datePicker setDate:disabledDate animated:YES];
}
}
-(void)getDisableDate
{
?????
}
- (void)LabelChange:(id)sender{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd.MM.yyyy HH:mm"];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"IT"];
[self.datePicker setLocale:locale];
labelDate.text = [NSString stringWithFormat:#"%#",
[df stringFromDate:datePicker.date]];
NSLog(#"date:%#", datePicker.date);
}
UIDatePicker doesn't support ranges of dates. What I would do instead is to change the date whenever a bad date is selected, by using setDate:animated: to the nearest date that is selectable. Also, to show a message somewhere explaining why the selected date was changed.
Either that, or, write your own custom UIDatePicker using UIPickerView. Not too hard, I've done it before. The worst part is dealing with wrapping values (eg: 31 -> 1). Does involve more work, though.
Best solution is create custom UIDatePicker using UIPickerView it's too easy and in future you can do changes easily.
Check the link.

Save value from Action Sheet

I am stuck on something dumb. This app is an OSX core-data app. I'm calling an action sheet to play with dates. The date selected is correctly shown on the screen after the sheet is closed. However, I cannot figure how to save the date.
Any help appreciated. This is the code I'm working with in my AppDelegate.m:
NSDate *theDate = [self.purchaseDatePicker dateValue];
if (theDate)
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSString *formattedDateString;
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
formattedDateString = [formatter stringFromDate:theDate];
[self.purchaseDate setStringValue: formattedDateString];
self.item.purchaseDate = theDate;
[self.item setPurchaseDate:theDate];
[self.item setPurchaseDate:self.item.purchaseDate];
NSLog(#"theDate is %#", theDate); <-- this is fine.
NSLog(#"item.purchaseDate is %#", self.item.purchaseDate); <-- this returns NULL
NSError *error = nil;
NSManagedObjectContext *moc = _coreDataController.mainThreadContext;
if (![moc save:&error])
{
[[NSApplication sharedApplication] presentError:error];
}
}
}
I found the answers here very helpful, but this post really got me thinking. So today, the code looks like below, and it works great!!
1.
[itemArrayController setValue: [DatePicker1 dateValue] forKeyPath: #"selection.date1"];
2.
if ([itemArrayController valueForKeyPath: #"selection.date1"] == NULL) {
date1 = [NSDate date];
[datePicker1 setDateValue: date1];
} else {
[datePicker1 setDateValue: [itemArrayController valueForKeyPath: #"selection.date1"]];
date1 = [itemArrayController valueForKeyPath: #"selection.date1"];
}

InputAccessoryView of a UITextField

I need to stick a toolBar with a UITextField inside to a keyboard.
What if I make the whole toolBar (which I think is the textField's super view) the inputAccessoryView of its textField?
I mean like this:
textField.inputAccessoryView = toolBar; // textField is inside the toolBar
I've been trying on this but I have not made it work yet.
Anyone can help?
Or is there another way to achieve what I want?
- (void)viewDidLoad
{
[self createAccessoryView];
[textField setDelegate:self];
[textField setKeyboardType:UIKeyboardTypeDefault];
[textField setInputAccessoryView:fieldAccessoryView];
}
- (void)createAccessoryView
{
CGRect frame = CGRectMake(0.0, self.view.bounds.size.height, self.view.bounds.size.width, 44.0);
fieldAccessoryView = [[UIToolbar alloc] initWithFrame:frame];
fieldAccessoryView.barStyle = UIBarStyleBlackOpaque;
fieldAccessoryView.tag = 200;
[fieldAccessoryView setBarStyle:UIBarStyleBlack];
UIBarButtonItem *spaceButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(done:)];
UISegmentedControl* segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:NSLocalizedString(#"Previous", #""), NSLocalizedString(#"Next", #""), nil]];
[segmentedControl addTarget:self action:#selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
[segmentedControl setMomentary:YES];
UIBarButtonItem *segmentButton = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
[fieldAccessoryView setItems:[NSArray arrayWithObjects:segmentButton, spaceButton, doneButton, nil] animated:NO];
[segmentButton release];
[spaceButton release];
[doneButton release];
[segmentedControl release];
}
When are you setting the property? You may be setting it after the view has already loaded.
Try setting it in
- (void) viewDidLoad

NSTimer wont stop [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
NSTimer doesn't stop
I am having a hard time stopping my timer, witch pings to my server.
I already searched for other answers here and on other places, but i can`t seem to find where i have gone wrong.
I decided to make an example code with the same idea, but, you click a button the timer starts, you click another the timer ends, and it worked the way it should. Please don't mind if i did something wrong (other than the timer part) i'm new in this. All i want to know is why won`t it stop..
Thanks in advance.
Connection.h
#import <Foundation/Foundation.h>
#interface Connection : NSObject
{
NSString *urlString;
NSURL *url;
NSMutableURLRequest *request;
NSURLConnection *connection;
NSURLResponse *response;
NSMutableData *receivedData;
NSData *responseData;
NSError *error;
NSTimer *timer;
}
#property (nonatomic, retain) NSTimer *timer;
-(BOOL)authenticateUser:(NSString *)userName Password:(NSString *)password;
-(BOOL)checkConnection;
-(void)ping:(NSTimer *)aTimer;
-(void)logout;
-(void)timerStart;
-(void)timerStop;
#end
Connection.m
#import "Connection.h"
#import "Parser.h"
#import "Reachability.h"
#import "TBXML.h"
#implementation Connection
#synthesize timer;
-(BOOL) authenticateUser:(NSString *)userName Password:(NSString *)password
{
BOOL success;
urlString = [[NSString alloc] initWithFormat:#"my/server/address/login"];
url =[[NSURL alloc] initWithString:urlString];
request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
error = [[NSError alloc] init];
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[responseData retain];
NSString *tempString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSMutableDictionary *tempDict= [[NSMutableDictionary alloc] init];
if (request)
{
Parser *parser = [[Parser alloc] init];
tempDict = [parser readXMLString:tempString];
for (id key in tempDict)
{
NSLog(#"%# is %#",key,[tempDict objectForKey:key]);
}
if ([[tempDict objectForKey:#"login"] isEqualToString:#"true"] )
{
success = YES;
self.timerStart;
}
else
{
success = NO;
}
}
[urlString release];
[url release];
[error release];
[responseData release];
[tempString release];
return success;
}
-(void)logout
{
self.timerStop;
}
-(void)ping:(NSTimer *)aTimer;
{
urlString = [[NSString alloc] initWithFormat:#"my/server/address"];
url =[[NSURL alloc] initWithString:urlString];
request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
NSLog(#"ping");
[urlString release];
[url release];
}
-(BOOL)checkConnection
{
Reachability *reachability = [Reachability reachabilityWithHostName:#"http://my/server/address"];
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
return NO;
}
else
{
return YES;
}
}
-(void)timerStart
{
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(ping:) userInfo:nil repeats:YES];
}
-(void)timerStop
{
[self.timer invalidate];
self.timer = nil;
}
#end
In timerStart you just replace whatever is in the timer property. If you start a second timer without stopping the first one, it will run forever. So timerStart should first call timerStop before creating a new one (and should probably have a new name then as it would be silly to call timerStop from timerStart).
Use [self timerStop]; using dot syntax is ONLY for properties (and will generate a warning if you don't), not calling a method in the way you're doing it.
Edit: This won't fix your problem, but doing it the way you are is very bad coding practice
-(void)timerStart
{
[self.timer invalidate];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:#selector(ping:) userInfo:nil repeats:YES];
}

NSTimer Troubles

I am trying to run the code below but it keeps locking up my simulator after the "Tick" is written to the console. It never outputs "Tock" so my guess is that it has to do with the line "NSTimeInterval elapsedTime = [startTime timeIntervalSinceNow];" The IBactions are activated by buttons. timer and startTime are defined in the .h as NSTimer and NSDate respectively.
Can anyone tell me what I am doing wrong?
code:
- (IBAction)startStopwatch:(id)sender
{
startTime = [NSDate date];
NSLog(#"%#", startTime);
timer = [NSTimer scheduledTimerWithTimeInterval:1 //0.02
target:self
selector:#selector(tick:)
userInfo:nil
repeats:YES];
}
- (IBAction)stopStopwatch:(id)sender
{
[timer invalidate];
timer = nil;
}
- (void)tick:(NSTimer *)theTimer
{
NSLog(#"Tick!");
NSTimeInterval elapsedTime = [startTime timeIntervalSinceNow];
NSLog(#"Tock!");
NSLog(#"Delta: %d", elapsedTime);
}
I have the following in the .h:
#interface MainViewController : UIViewController <FlipsideViewControllerDelegate> {
NSTimer *timer;
NSDate *startTime;
}
- (IBAction)startStopwatch:(id)sender;
- (IBAction)stopStopwatch:(id)sender;
- (void)tick:(NSTimer *)theTimer;
#property(nonatomic, retain) NSTimer *timer;
#property(nonatomic, retain) NSDate *startTime;
#end
Where you have:
startTime = [NSDate date];
You need:
startTime = [[NSDate date] retain];
Anything that is created with out an alloc, new, init will be auto-released (rule of thumb). So what is happening is you are creating the NSDate, assigning it to startTime, it's getting auto-released (destroyed), then you are trying to call timeIntervalSinceNow on an object that was fully released so it blows up.
Adding the retain increased the retain count so it still sticks around after the auto-release. Don't forget to manually release it when you're done with it though!
To take advantage of the #property you need to do:
self.startTime = [NSDate date]

Resources