I am getting mixed results from random number code - objective-c

for a class project we've been asked to create an app. In part my app includes a coin counting app where a random amount is generated and the user is required to click on the coin buttons until the correct amount is reached.
here is the .m code...
//
// CountingChangeViewController.m
// Piggy Bank
//
#import "CountingChangeViewController.h"
#interface CountingChangeViewController ()
//define button connections
- (IBAction)PennyButton:(id)sender;
- (IBAction)NickelButton:(id)sender;
- (IBAction)DimeButton:(id)sender;
- (IBAction)QuarterButton:(id)sender;
- (IBAction)ResetButton:(id)sender;
//define UILable connections
#property (weak, nonatomic) IBOutlet UILabel *labelAmountRequired;
#property (weak, nonatomic) IBOutlet UILabel *labelAmountInBank;
#property (weak, nonatomic) IBOutlet UILabel *labelAmountRemaining;
#property (weak, nonatomic) IBOutlet UILabel *labelCoinCount;
#property (weak, nonatomic) IBOutlet UIImageView *imagePickNewCoin;
#property (weak, nonatomic) IBOutlet UILabel *labelPennyCount;
#property (weak, nonatomic) IBOutlet UILabel *labelNickelCount;
#property (weak, nonatomic) IBOutlet UILabel *labelDimeCount;
#property (weak, nonatomic) IBOutlet UILabel *labelQuarterCount;
#end
//declare class variables
double AmountTotal = 0;
double AmountBank = 0;
double AmountRemaining = 0;
double rNumberMod;
double coinValue;
int coinCount = 0;
int pennyCount = 0;
int nickelCount = 0;
int dimeCount = 0;
int quarterCount = 0;
//start implementation
#implementation CountingChangeViewController
- (void)resetPage{
_imagePickNewCoin.hidden=YES;
//simply generates a new random amount
AmountTotal = [self RandomNumber];
_labelAmountRequired.text = [NSString stringWithFormat:#"$%.2f", AmountTotal];
AmountBank = 0;
_labelAmountInBank.text = [NSString stringWithFormat:#"$%.2f", AmountBank];
AmountRemaining = 0;
_labelAmountRemaining.text = [NSString stringWithFormat:#"$%.2f", AmountRemaining];
coinCount = 0;
_labelCoinCount.text = [NSString stringWithFormat:#"%d", coinCount];
pennyCount = 0;
_labelPennyCount.text = [NSString stringWithFormat:#"%d", pennyCount];
nickelCount = 0;
_labelNickelCount.text = [NSString stringWithFormat:#"%d", nickelCount];
dimeCount = 0;
_labelDimeCount.text = [NSString stringWithFormat:#"%d", dimeCount];
quarterCount = 0;
_labelQuarterCount.text = [NSString stringWithFormat:#"%d", quarterCount];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self resetPage];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)PennyButton:(id)sender {
pennyCount++;
_labelPennyCount.text =[NSString stringWithFormat:#"%d",pennyCount];
coinValue = .01;
[self checkValue];
}
- (IBAction)NickelButton:(id)sender {
if ((AmountRemaining > 0) && (AmountRemaining <= .04))
{
//display the error message
_imagePickNewCoin.hidden=NO;
}
else
{
nickelCount++;
_labelNickelCount.text =[NSString stringWithFormat:#"%d",nickelCount];
coinValue = .05;
[self checkValue];
}
}
- (IBAction)DimeButton:(id)sender {
if ((AmountRemaining > 0) && (AmountRemaining <= .09))
{
//display the error message
_imagePickNewCoin.hidden=NO;
}
else
{
dimeCount++;
_labelDimeCount.text =[NSString stringWithFormat:#"%d",dimeCount];
coinValue = .10;
[self checkValue];
}
}
- (IBAction)QuarterButton:(id)sender {
if ((AmountRemaining > 0) && (AmountRemaining <= .24))
{
//display the error message
_imagePickNewCoin.hidden=NO;
}
else
{
quarterCount++;
_labelQuarterCount.text =[NSString stringWithFormat:#"%d",quarterCount];
coinValue = .25;
[self checkValue];
}
}
-(double)RandomNumber{
int rNumber = arc4random_uniform(99) +1;
double rNumberMod = rNumber * .01;
return rNumberMod;
}
-(void)checkValue {
//hide the error message
_imagePickNewCoin.hidden=YES;
//at button press play coin drop sound
SystemSoundID soundID;
NSString *soundFile = [[NSBundle mainBundle]
pathForResource :#"coin-drop-1" ofType :#"mp3"];
AudioServicesCreateSystemSoundID ((__bridge CFURLRef)
[NSURL fileURLWithPath :soundFile]
, &soundID);
AudioServicesPlaySystemSound (soundID);
//add coinvalue to amountTotal and put the resulting value in the AmountInBank UILabel .text attribute
//this is the math occuring behind the scenes
AmountBank = AmountBank + coinValue;
//this is how the math result shows on the screen
_labelAmountInBank.text = [NSString stringWithFormat:#"$%.2f", AmountBank];
//calculate the amountRemaining and put the resulting value in the AmountRemaining UILabel .text attribute
//this is the math occuring behind the scenes
AmountRemaining = AmountTotal - AmountBank;
//this is how the math result shows on the screen
_labelAmountRemaining.text = [NSString stringWithFormat:#"$%.2f", AmountRemaining];
// increment coin count by one and display it on the screen
coinCount++;
_labelCoinCount.text =[NSString stringWithFormat:#"%d",coinCount];
//test to see if the AmountRemaining = 0
if (AmountRemaining == 0)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"CONGRATULATIONS!" message:#"You saved the correct amount of money! Would you like to try again?" delegate:self cancelButtonTitle:nil otherButtonTitles:#"TRY AGAIN", nil];
[alertView show];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0)
[self resetPage];
}
- (IBAction)ResetButton:(id)sender {
[self resetPage];
}
#end
Sometimes it works and sometimes it doesn't. It is supposed to bring up an alert view when the amount of change needed reaches 0. Sometimes it does and other times it doesn't. Also when amountRemaining is less than the value of the coin button clicked it is supposed to show a hidden image "imagePickNewCoin" instead of adding the coin's value to the bank amount. Sometimes this works and other times it performes the calculation anyway resulting in a negative value for amountRemaining.
Why would this work sometimes and not other times?

Related

Getting a current value from UIProgressView, and triggering an event when a threshold is met

I have several UIProgressViews that read the voltage of an external device attached to the iOS device. The view scales it from 0-5 volts and I wanted to know if there was a way to retrieve the current progress/voltage of the UIProgressView and compare it to a threshold that is input by a user. Once this threshold is surpassed; a method I have written should be called.
The problem isn't necessarily the comparison part or calling the method. I am having trouble retrieving a live update of what the current value of the progressview is.
Thanks for your time.
EDIT FOR PART II:
So the problem is I did not code this and it is code pertaining to a certain product called the Nanospark board. This board is an input/output control board for factory systems that is run by various iOS devices.
I cannot quite seem to figure out what the previous coder did within this class:
//
// AnalogVC.m
// NanosparkController
//
#import "AnalogVC.h"
#import "AppDelegate.h"
#interface InputItem : NSObject
#property (weak,nonatomic) UISwitch *onSwitch;
#property (weak,nonatomic) UIProgressView *progressView;
#property (weak,nonatomic) UILabel *valueLabel;
#end
#implementation InputItem
AppDelegate *appDelegate;
+ (id)itemWithSwitch:(id)temp progress:(id)progress label:(id)label
{
InputItem *item = [[InputItem alloc] init];
item.onSwitch = temp;
item.progressView = progress;
item.valueLabel = label;
return item;
}
- (void)setDisconnected
{
self.onSwitch.on = NO;
self.onSwitch.enabled = NO;
self.valueLabel.text = #"0.000 v";
self.progressView.progress = 0;
}
- (void)setOn
{
self.onSwitch.on = YES;
self.onSwitch.enabled = YES;
self.valueLabel.text = #"0.000 v";
self.progressView.progress = 0;
[appDelegate watchPins:#"testing ON"];
}
- (void)setOff
{
self.onSwitch.on = NO;
self.onSwitch.enabled = YES;
self.valueLabel.text = #"0.000 v";
self.progressView.progress = 0;
[appDelegate watchPins:#"testing OFF"];
}
- (void)setValue:(double)value
{
if (self.onSwitch.on)
{
self.valueLabel.text = [NSString stringWithFormat:#"%0.3f v",value];
self.progressView.progress = value/5.0;
if(value > 0.8){
[appDelegate watchPins:#"testing VALUE"];
}
}
}
#end
#interface AnalogVC ()
{
NSArray *_inputItems;
AppDelegate *appDelegate;
NSMutableArray *channel0Values;
UIColor *custom1;
UIColor *custom2;
UIColor *custom3;
UIColor *custom4;
}
#property (nonatomic) NCBoardManager *manager;
#property (weak,nonatomic) IBOutlet UISwitch *inputSwitch0;
#property (weak,nonatomic) IBOutlet UISwitch *inputSwitch1;
#property (weak,nonatomic) IBOutlet UISwitch *inputSwitch2;
#property (weak,nonatomic) IBOutlet UISwitch *inputSwitch3;
#property (weak,nonatomic) IBOutlet UISwitch *inputSwitch4;
#property (weak,nonatomic) IBOutlet UISwitch *inputSwitch5;
#property (weak,nonatomic) IBOutlet UIProgressView *inputProgress0;
#property (weak,nonatomic) IBOutlet UIProgressView *inputProgress1;
#property (weak,nonatomic) IBOutlet UIProgressView *inputProgress2;
#property (weak,nonatomic) IBOutlet UIProgressView *inputProgress3;
#property (weak,nonatomic) IBOutlet UIProgressView *inputProgress4;
#property (weak,nonatomic) IBOutlet UIProgressView *inputProgress5;
#property (weak,nonatomic) IBOutlet UILabel *inputValue0;
#property (weak,nonatomic) IBOutlet UILabel *inputValue1;
#property (weak,nonatomic) IBOutlet UILabel *inputValue2;
#property (weak,nonatomic) IBOutlet UILabel *inputValue3;
#property (weak,nonatomic) IBOutlet UILabel *inputValue4;
#property (weak,nonatomic) IBOutlet UILabel *inputValue5;
#property (weak,nonatomic) IBOutlet UISlider *outputSlider0;
#property (weak,nonatomic) IBOutlet UISlider *outputSlider1;
#property (weak,nonatomic) IBOutlet UIStepper *outputStepper0;
#property (weak,nonatomic) IBOutlet UIStepper *outputStepper1;
#property (weak,nonatomic) IBOutlet UILabel *outputValue0;
#property (weak,nonatomic) IBOutlet UILabel *outputValue1;
- (IBAction)inputChannelChanged:(UISwitch *)sender;
- (IBAction)outputSliderMoved:(UISlider *)sender;
- (IBAction)outputSliderStopped:(UISlider *)sender;
- (IBAction)outputStepperChanged:(UIStepper *)sender;
#end
#implementation AnalogVC{}
//////////////////////////////
#pragma mark View Lifecycle
//////////////////////////////
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"Analog VC loaded");
_inputItems = #[[InputItem itemWithSwitch:_inputSwitch0 progress:_inputProgress0 label:_inputValue0],
[InputItem itemWithSwitch:_inputSwitch1 progress:_inputProgress1 label:_inputValue1],
[InputItem itemWithSwitch:_inputSwitch2 progress:_inputProgress2 label:_inputValue2],
[InputItem itemWithSwitch:_inputSwitch3 progress:_inputProgress3 label:_inputValue3],
[InputItem itemWithSwitch:_inputSwitch4 progress:_inputProgress4 label:_inputValue4],
[InputItem itemWithSwitch:_inputSwitch5 progress:_inputProgress5 label:_inputValue5]];
_manager = [NCBoardManager sharedBoardManager];
__unsafe_unretained AnalogVC *vc = self;
[_manager setAnalogInputHandling:dispatch_get_main_queue()
filter:^(NCAnalogInputs *inputs){ return YES; }
handler:^(NCAnalogInputs *inputs){ [vc setAnalogInputs:inputs]; }];
// Register for notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(boardConnected:)
name:CONNECTED_NOTIFICATION
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(boardDisconnected:)
name:DISCONNECTED_NOTIFICATION
object:nil];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self updateAnalogInputs];
[self updateAnalogOutputs];
custom1 = [UIColor whiteColor];
custom2 = [UIColor darkGrayColor];
custom3 = [UIColor blackColor];
custom4 = [UIColor colorWithRed:.97 green:.97 blue:.588 alpha:1.0];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[custom2 CGColor], (id)[custom1 CGColor], (id)[custom2 CGColor], nil];
gradient.startPoint = CGPointMake(0.5, 0);
gradient.endPoint = CGPointMake(0.5, 1.0);
gradient.locations = [NSArray arrayWithObjects: [NSNumber numberWithFloat:0.0], [NSNumber numberWithFloat:0.5], [NSNumber numberWithFloat:1.0], nil];
[self.view.layer insertSublayer:gradient atIndex:0];
[self.inputSwitch0 setOnTintColor:custom4];
[self.inputSwitch1 setOnTintColor:custom4];
[self.inputSwitch2 setOnTintColor:custom4];
[self.inputSwitch3 setOnTintColor:custom4];
[self.inputSwitch4 setOnTintColor:custom4];
[self.inputSwitch5 setOnTintColor:custom4];
[self.inputSwitch0 setTintColor:custom3];
[self.inputSwitch1 setTintColor:custom3];
[self.inputSwitch2 setTintColor:custom3];
[self.inputSwitch3 setTintColor:custom3];
[self.inputSwitch4 setTintColor:custom3];
[self.inputSwitch5 setTintColor:custom3];
self.inputProgress0.trackTintColor = custom3;
self.inputProgress1.trackTintColor = custom3;
self.inputProgress2.trackTintColor = custom3;
self.inputProgress3.trackTintColor = custom3;
self.inputProgress4.trackTintColor = custom3;
self.inputProgress5.trackTintColor = custom3;
self.inputProgress0.progressTintColor = custom4;
self.inputProgress1.progressTintColor = custom4;
self.inputProgress2.progressTintColor = custom4;
self.inputProgress3.progressTintColor = custom4;
self.inputProgress4.progressTintColor = custom4;
self.inputProgress5.progressTintColor = custom4;
self.outputSlider0.minimumTrackTintColor = custom4;
self.outputSlider1.minimumTrackTintColor = custom4;
self.outputSlider0.maximumTrackTintColor = custom3;
self.outputSlider1.maximumTrackTintColor = custom3;
self.outputSlider0.thumbTintColor = custom3;
self.outputSlider1.thumbTintColor = custom3;
if(_manager.isBoardConnected)
{
self.outputStepper0.tintColor = custom4;
self.outputStepper1.tintColor = custom4;
self.outputStepper0.enabled = TRUE;
self.outputStepper1.enabled = TRUE;
self.outputSlider0.enabled = TRUE;
self.outputSlider1.enabled = TRUE;
}
else
{
self.outputStepper0.tintColor = custom2;
self.outputStepper1.tintColor = custom2;
self.outputStepper0.enabled = FALSE;
self.outputStepper1.enabled = FALSE;
self.outputSlider0.enabled = FALSE;
self.outputSlider1.enabled = FALSE;
}
}
//////////////////////////////
#pragma mark Rotation Calls
//////////////////////////////
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationPortrait;
}
- (BOOL)shouldAutorotate
{
return FALSE;
}
//////////////////////////
#pragma mark Board Calls
//////////////////////////
- (void)boardConnected:(NSNotification *)notification
{
[self updateAnalogInputs];
[self updateAnalogOutputs];
self.outputStepper0.enabled = TRUE;
self.outputStepper1.enabled = TRUE;
self.outputSlider0.enabled = TRUE;
self.outputSlider1.enabled = TRUE;
self.outputStepper0.tintColor = custom4;
self.outputStepper1.tintColor = custom4;
}
- (void)boardDisconnected:(NSNotification *)notification
{
[self updateAnalogInputs];
[self updateAnalogOutputs];
self.outputStepper0.enabled = FALSE;
self.outputStepper1.enabled = FALSE;
self.outputSlider0.enabled = FALSE;
self.outputSlider1.enabled = FALSE;
self.outputStepper0.tintColor = custom2;
self.outputStepper1.tintColor = custom2;
}
- (void)updateAnalogInputs
{
uint8_t channel = self.manager.analogInputChannels;
switch (self.manager.analogInputStatus)
{
case NCInputConnected:
// Check if channels we left on
if (channel) self.manager.analogInputChannels = 0;
[_inputItems makeObjectsPerformSelector:#selector(setOff)];
break;
case NCInputDisconnected:
[_inputItems makeObjectsPerformSelector:#selector(setDisconnected)];
break;
case NCInputLiveUpdating:
for (InputItem *item in _inputItems)
{
//if (channel & 1) [item setOn];
//else [item setOff];
channel >>= 1;
}
break;
case NCInputSampling:
[_inputItems makeObjectsPerformSelector:#selector(setDisconnected)];
break;
case NCInputTransfering:
[_inputItems makeObjectsPerformSelector:#selector(setDisconnected)];
break;
}
}
- (void)setAnalogInputs:(NCAnalogInputs *)inputs
{
int i = 0;
uint8_t channels = inputs.channels;
for (InputItem *item in _inputItems)
{
if (channels & 1)
{
[item setValue:[inputs valueForChannel:i]];
}
channels >>= 1;
i++;
}
}
- (void)updateAnalogOutputs
{
BOOL connected = [self.manager isBoardConnected];
self.outputSlider0.value = self.manager.analogOutput0;
self.outputSlider0.enabled = connected;
self.outputStepper0.value = self.outputSlider0.value * 1000;
self.outputStepper0.enabled = connected;
self.outputValue0.text = [NSString stringWithFormat:#"%0.3f v",self.outputSlider0.value];
self.outputSlider1.value = self.manager.analogOutput1;
self.outputSlider1.enabled = connected;
self.outputStepper1.value = self.outputSlider1.value * 1000;
self.outputStepper1.enabled = connected;
self.outputValue1.text = [NSString stringWithFormat:#"%0.3f v",self.outputSlider1.value];
}
///////////////////////////////
#pragma mark IBAction Methods
///////////////////////////////
- (IBAction)inputChannelChanged:(UISwitch *)sender
{
NSLog(#"TEST");
InputItem *item = [_inputItems objectAtIndex:sender.tag];
uint8_t channels = self.manager.analogInputChannels;
if (sender.on)
{
channels |= (1 << sender.tag);
[item setOn];
}
else
{
channels &= ~(1 << sender.tag);
[item setOff];
}
if (!self.manager.analogInputChannels) [self.manager startAnalogLiveUpdating];
else if(!channels) [self.manager stopAnalogLiveUpdating];
self.manager.analogInputChannels = channels;
}
- (IBAction)outputSliderMoved:(UISlider *)sender
{
if (!sender.tag)
{
self.manager.analogOutput0 = sender.value;
self.outputValue0.text = [NSString stringWithFormat:#"%0.3f v",sender.value];
}
else
{
self.manager.analogOutput1 = sender.value;
self.outputValue1.text = [NSString stringWithFormat:#"%0.3f v",sender.value];
}
}
- (IBAction)outputSliderStopped:(UISlider *)sender
{
if (!sender.tag)
{
self.manager.analogOutput0 = sender.value;
self.outputStepper0.value = round(sender.value * 1000.0);
self.outputValue0.text = [NSString stringWithFormat:#"%0.3f v",self.outputStepper0.value/1000.0];
}
else
{
self.manager.analogOutput1 = sender.value;
self.outputStepper1.value = round(sender.value * 1000.0);
self.outputValue1.text = [NSString stringWithFormat:#"%0.3f v",self.outputStepper1.value/1000.0];
}
}
- (IBAction)outputStepperChanged:(UIStepper *)sender
{
float value = sender.value/1000.0;
if (!sender.tag)
{
self.manager.analogOutput0 = value;
self.outputSlider0.value = value;
self.outputValue0.text = [NSString stringWithFormat:#"%0.3f v",value];
}
else
{
self.manager.analogOutput1 = sender.value/1000.0;
self.outputSlider1.value = value;
self.outputValue1.text = [NSString stringWithFormat:#"%0.3f v",value];
}
}
#end
The problem I am having is I cannot figure out how to take values to and from the UIProgressViews that are on the storyboard (which is, like you said, a trivial concept). However with this set up it is rather convoluted.
Second problem is that; I am not sure if there is a way I can debug this as the application only runs when the external device (the nanospark controller board) is connected to the iPod.
The last but final problem I am having is that I am assuming the IBAction InputChannelChanged is being called (cannot debug this regularly with a breakpoint as aforementioned because it requires the external device to run the application), but when I run the application it does everything it should and the buttons react correctly to what the original software developer had coded.
This means that if I add my texting method to the IBAction (by adding [appDelegate watchPins#"TEST"]) it does not send the text to the user, but the buttons do still do what they should have done in concordance to the previous developers' aspirations.... this implies that the IBAction method is indeed being called... but then why isn't my text going through? I know that [appDelegate watchPins:#"TEST"]; should work as I have used it within several of his other classes.
Here is a screenshot displaying the UI of the AnalogVC.m:
http://i.stack.imgur.com/NNpZk.png
Do not feel obligated to answer all of these questions it's just I felt it necessary to provided all three for greater context of the problem. Thanks and sorry for the TL;DR.
EDIT 2: I'd upload the image but I do not have the required minimum reputation.
EDIT 3: I have tried to add another IBAction just to see if the buttons react to that; still nothing even if I copied the exact code from the other working classes.
Solution 1:
You need to call your method when you update the UIProgressView I assume that use are using the setProgress: animated: method somewhere in your code to update the progress view. If so, try this code in the method in which you update the UIProgressView:
float myVoltageFromDevice = self.deviceInput / 5.0; //this can be whatever your input is mapped to 0.0...1.0
//the self.device input variable should be the input from the external device.
if(myFloatFromDevice > myThreshold){ //set my threshold to whatever you would like.
[self doAction]; //do whatever you need to do when the value is surpassed
}else{
[myProgressView setProgress:myVoltageFromDevice animated: NO];
}
Edit:
I commented in the code above //this can be whatever your input is mapped to 0.0...1.0. Just in case this isn't clear, to achieve mapping you would do:
float myVoltageFromDevice = self.deviceInput / 5.0;
because the device input variable should be a value from 0-5 as you said in the OP. This makes the value from 0.0-1.0 which is the range of values that UIProgressView will accept.
Solution 2:
If can't pull off the above (which you really should be able to do), you should use Key Value Observing (KVO) which is detailed in this apple developer doc.
Edit 2:
The code you posted is quite complicated, but I believe that the method that you need to edit is - (void)setAnalogInputs:(NCAnalogInputs *)inputs try changing some of the code to this:
for (InputItem *item in _inputItems)
{
if (channels & 1)
{
if([inputs valueForChannel:i] > myThreshold){
[self doAction]; //Do your action here.
}else{
[item setValue:[inputs valueForChannel:i]];
}
}
channels >>= 1;
i++;
}

Cannot compile with error, not sure what to do

I am Getting error message as follows...
"2014-01-28 21:17:56.878 Higher or Lower 2[5869:70b] * Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key enterButoonOut.'
* First throw call stack:"
//
// ViewController.m
// Higher or Lower 2
//
// Created by Michael Goedken on 1/27/14.
// Copyright (c) 2014 Michael Goedken. All rights reserved.
//
/
// Created by Michael Goedken on 1/27/14.
// Copyright (c) 2014 Michael Goedken. All rights reserved.
//
#import "ViewController.h"
int answer = 0;
int guess = 0;
int turn = 0;
BOOL timeStarted = NO;
#interface ViewController ()
#end
#implementation ViewController
- (IBAction)enterButton:(id)sender {
NSString *input = _labelGuess.text;
guess = [input intValue];
_previousLabel.text = [NSString stringWithFormat:#"%d",guess];
_labelGuess.text=#"";
turn++;
_guessesLabel.text = [NSString stringWithFormat:#"%d",turn];
if (timeStarted == NO){
seconds = 0;
timer = [NSTimer scheduledTimerWithTimeInterval:.001 target:self
selector:#selector(countUp) userInfo:nil repeats:YES];
}
timeStarted = YES;
if (guess < 1 || guess > 100){
_correct.hidden = YES;
_lower.hidden = YES;
_higher.hidden = YES;
_chooseNumber.hidden = YES;
_outOfRange.hidden = NO;
}
else if (guess > answer) {
_lower.hidden = NO;
_higher.hidden = YES;
_chooseNumber.hidden = YES;
_correct.hidden = YES;
_outOfRange.hidden = YES;
}
else if (guess < answer) {
_lower.hidden = YES;
_higher.hidden = NO;
_chooseNumber.hidden = YES;
_correct.hidden = YES;
_outOfRange.hidden = YES;
}
else {
_correct.hidden = NO;
_lower.hidden = YES;
_higher.hidden = YES;
_chooseNumber.hidden = YES;
_outOfRange.hidden = YES;
[timer invalidate];
_nextButtonOut.hidden = NO;
_enterButtonOut.hidden = YES;
_labelGuess.hidden = YES;
}
}
-(void) countUp {
milliSeconds ++;
seconds = milliSeconds / 1000;
minutes = seconds / 60;
remainingSeconds = seconds % 60;
remainingMilliSeconds = milliSeconds % 1000;
if (minutes > 0) {
_timerLabel.text = [NSString stringWithFormat:#"%2d:%.2d", minutes, remainingSeconds];
}
else {
_timerLabel.text = [NSString stringWithFormat:#"%2d:%.2d.%.3d", minutes,
remainingSeconds, remainingMilliSeconds];
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[_labelGuess resignFirstResponder];
}
- (void)viewDidLoad
{
[super viewDidLoad];
_labelGuess.keyboardType = UIKeyboardTypeNumberPad;
_higher.hidden = YES;
_lower.hidden = YES;
_correct.hidden = YES;
_outOfRange.hidden = YES;
answer = arc4random() % 100 + 1;
_nextButtonOut.hidden = YES;
NSLog(#"Answer %i", answer);
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)nextButton:(id)sender {
_correct.hidden = YES;
_lower.hidden = YES;
_higher.hidden = YES;
_chooseNumber.hidden = YES;enter code here
_outOfRange.hidden = YES;
_labelGuess.hidden = YES;
_guessesLabel.hidden = YES;
_previousLabel.hidden = YES;
_timerLabel.hidden = YES;
_nextButtonOut.hidden = YES;
_enterButtonOut.hidden = YES;
_background.hidden = YES;
_guesses.hidden = YES;
_previous.hidden = YES;
}
#end
//
// ViewController.h
// Higher or Lower 2
//
// Created by Michael Goedken on 1/27/14.
// Copyright (c) 2014 Michael Goedken. All rights reserved.
//
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController {
NSTimer *timer;
int seconds;
int minutes;
int remainingSeconds;
int milliSeconds;
int remainingMilliSeconds;
}
#property (weak, nonatomic) IBOutlet UIImageView *chooseNumber;
#property (weak, nonatomic) IBOutlet UITextField *labelGuess;
#property (weak, nonatomic) IBOutlet UIImageView *higher;
#property (weak, nonatomic) IBOutlet UIImageView *lower;
#property (weak, nonatomic) IBOutlet UIImageView *correct;
#property (weak, nonatomic) IBOutlet UIImageView *outOfRange;
#property (weak, nonatomic) IBOutlet UILabel *previousLabel;
#property (weak, nonatomic) IBOutlet UILabel *timerLabel;
#property (weak, nonatomic) IBOutlet UIButton *nextButtonOut;
#property (weak, nonatomic) IBOutlet UIButton *enterButtonOut;
#property (weak, nonatomic) IBOutlet UIImageView *background;
#property (weak, nonatomic) IBOutlet UILabel *previous;
#property (weak, nonatomic) IBOutlet UILabel *guessesLabel;
#property (weak, nonatomic) IBOutlet UILabel *guesses;
- (IBAction)nextButton:(id)sender;
- (IBAction)enterButton:(id)sender;
#end
I normally get this error message when one of a few things happens.
1) I have misspelled the value for segue.identifier as I'm about to segue to another module (not sure this applies in your case, but that is where it always gets me).
2) If you make changes to a storyboard, then go delete the value in code, the connection does not get eliminated in your storyboard and you have to manually go in and delete the link from within storyboard. To check, just right click (or ctrl click) on each element in a storyboard and note the connections.
My guess is if you look at that button in the storyboard, you will see "enterButoonOut" instead of "enterButtonOut"
Hope this helps!
Glenn
You have misspelled enterButoonOut and it must be enterButtonOut as per your declaration:
#property (weak, nonatomic) IBOutlet UIButton *enterButtonOut;

objective c delegates

My program displays images with a timer. I want the user to be able to adjust the timer by using a UISlider.
I have a Deck class, which delegates and listens to another delegate 'SpeedSliderDelegate'. I want my Deck class to listen for changes from the SpeedSliderDelegate and update a value.
How do I set my Deck.m model to listen to SpeedSliderDelegate...(just after if(self = [super init] in Deck.m)
SpeedSliderDelegate.h
#protocol SpeedSliderDelegate <NSObject>
-(void)setSpeed:(float)currentSpeed;
#end
Deck.h
#import "SpeedSliderDelegate.h"
#import <Foundation/Foundation.h>
#import "Card.h"
#protocol DeckLooperDelegate <NSObject>
-(void)cardHasChangedTo:card1 aCard2:(Card *)card2 totalCount:(NSInteger)totalCount stopTimer:(NSTimer*)stopTimer cards:(NSArray *)cards;
#end
#interface Deck : NSObject <SpeedSliderDelegate>
#property (nonatomic, retain)NSMutableArray *cards;
#property (nonatomic, retain)NSTimer *timer;
#property (nonatomic, retain)id <DeckLooperDelegate> delegate;
#property (nonatomic)NSInteger total;
#property (nonatomic) float testSpeed;
- (NSInteger) cardsRemaining;
- (void) startTimerLoop;
#end
Deck.m
#import "Deck.h"
#import "Card.h"
#implementation Deck
#synthesize cards;
#synthesize timer;
#synthesize delegate;
#synthesize total, testSpeed;
- (id) init
{
if(self = [super init])
{
//self.delegate = self something like this...
cards = [[NSMutableArray alloc] init];
NSInteger aCount, picNum = 0;
for(int suit = 0; suit < 4; suit++)
{
for(int face = 1; face < 14; face++, picNum++)
{
if (face > 1 && face < 7)
aCount = 1;
else if (face > 6 && face < 10)
aCount = 0;
else
aCount = -1;
NSString* imagePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"card_%d", picNum] ofType:#"png"];
UIImage* theImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
Card *card = [[Card alloc] initWithFaceValue:(NSInteger)face
countValue:(NSInteger)aCount
suit:(Suit)suit
cardImage:(UIImage *)theImage];
[cards addObject:card];
}
}
}
return self;
}
-(void)setSpeed:(float)currentSpeed
{
testSpeed = currentSpeed;
}
-(void)startTimerLoop
{
if (!timer)
{
timer = [NSTimer scheduledTimerWithTimeInterval:testSpeed target:self
selector:#selector(timerEvent:) userInfo:nil repeats:YES ];
NSLog(#"Timer started!!!");
}
}
-(void)timerEvent:(NSTimer*)timer
{
srand(time(nil));
int index = rand()%[cards count];
Card *randomCard =[cards objectAtIndex:index];
[cards removeObjectAtIndex:index];
NSLog(#"%#" ,randomCard);
int index1 = rand()%[cards count];
Card *randomCard1 =[cards objectAtIndex:index1];
[cards removeObjectAtIndex:index1];
NSLog(#"%#" ,randomCard1);
total += (randomCard.countValue + randomCard1.countValue);
[self.delegate cardHasChangedTo:randomCard aCard2:randomCard1 totalCount:total stopTimer:self.timer cards:cards];
if ([cards count] == 0)
{
[self.timer invalidate];
self.timer = nil;
}
}
- (NSInteger) cardsRemaining
{
return [cards count];
}
- (NSString *) description
{
NSString *desc = [NSString stringWithFormat:#"Deck with %d cards\n",
[self cardsRemaining]];
return desc;
}
#end
GameViewController.h
#import "Deck.h"
#import "SpeedSliderDelegate.h"
#interface GameViewController : UIViewController <DeckLooperDelegate>
#property (nonatomic, retain) IBOutlet UIImageView *cardDisplay, *cardDisplay1;
#property (weak, nonatomic) IBOutlet UILabel *cardName, *cardName1;
#property (weak, nonatomic) IBOutlet UILabel *cardCount, *cardCount1;
#property (weak, nonatomic) IBOutlet UILabel *totalCount;
#property (nonatomic)int stop1;
#property (weak, nonatomic) IBOutlet UIButton *stopButton;
#property (weak, nonatomic) IBOutlet UIButton *restartButton;
#property (weak, nonatomic) IBOutlet UIButton *homeButton;
#property (weak, nonatomic) IBOutlet UISlider *speed;
#property (nonatomic, retain) id <SpeedSliderDelegate> delegate;
- (IBAction)start:(id)sender;
- (IBAction)stop:(id)sender;
- (IBAction)hideShow:(id)sender;
- (IBAction)homeAction:(id)sender;
#end
GameViewController.m
#import <QuartzCore/QuartzCore.h>
#import "GameViewController.h"
#import "Deck.h"
#implementation GameViewController
#synthesize cardDisplay, cardDisplay1, cardName, cardName1, cardCount, cardCount1, totalCount, stop1, stopButton, restartButton, homeButton, speed, delegate;
- (void)viewDidLoad
{
[super viewDidLoad];
Deck *deck = [[Deck alloc]init];
NSLog(#"%#", deck);
for (id cards in deck.cards)
{
NSLog(#"%#", cards);
}
deck.delegate = self;
[deck startTimerLoop];
cardDisplay.layer.cornerRadius = 7;
cardDisplay.clipsToBounds = YES;
cardDisplay1.layer.cornerRadius = 7;
cardDisplay1.clipsToBounds = YES;
[restartButton setHidden:YES];
[delegate setSpeed:speed.value];
}
//#pragma mark - DeckDelegate
-(void)cardHasChangedTo:(Card *)card1 aCard2:(Card *)card2 totalCount:(NSInteger)totalC stopTimer:(NSTimer *)stopTimer cards:(NSArray *)cards
{
[self.cardDisplay setImage:card1.cardImage];
[self.cardDisplay1 setImage:card2.cardImage];
self.cardName.text = card1.description;
self.cardName1.text = card2.description;
self.cardCount.text = [NSString stringWithFormat:#"%d", card1.countValue];
self.cardCount1.text = [NSString stringWithFormat:#"%d", card2.countValue];
self.totalCount.text = [NSString stringWithFormat:#"%d", totalC];
if (stop1 == 86)
{
[stopTimer invalidate];
stopTimer = nil;
}
if ([cards count] == 0)
{
[restartButton setHidden:NO];
}
}
- (IBAction)start:(id)sender
{
stop1 = 85;
[cardDisplay setHidden:YES];
[cardDisplay1 setHidden:YES];
self.totalCount.text = #"0";
self.cardCount.text = #"0";
self.cardCount1.text = #"0";
self.cardName.text = #"";
self.cardName1.text = #"";
Deck *deck = [[Deck alloc]init];
[NSTimer scheduledTimerWithTimeInterval:2 target:self
selector:#selector(cardDisplayDelay:) userInfo:nil repeats:NO];
NSLog(#"%#", deck);
deck.delegate = self;
[deck startTimerLoop];
cardDisplay.layer.cornerRadius = 7;
cardDisplay.clipsToBounds = YES;
cardDisplay1.layer.cornerRadius = 7;
cardDisplay1.clipsToBounds = YES;
[restartButton setHidden:YES];
}
- (IBAction)stop:(id)sender
{
stop1 = 86; //cancelled
[NSTimer scheduledTimerWithTimeInterval:2 target:self
selector:#selector(restartButtonDelay:) userInfo:nil repeats:NO];
}
-(void)restartButtonDelay:(NSTimer*)timer
{
[restartButton setHidden:NO];
}
-(void)cardDisplayDelay:(NSTimer*)timer
{
[cardDisplay setHidden:NO];
[cardDisplay1 setHidden:NO];
}
- (IBAction)hideShow:(id)sender
{
if ([cardCount isHidden])
{
[cardCount setHidden:NO];
[cardCount1 setHidden:NO];
[totalCount setHidden:NO];
}
else
{
[cardCount setHidden:YES];
[cardCount1 setHidden:YES];
[totalCount setHidden:YES];
}
}
- (IBAction)homeAction:(id)sender
{
stop1 = 86; //cancelled
}
#end
In the updating class .h
#protocol DoSomethingDelegate <NSObject>
-(void)doSomething;
#end
#property (assign, nonatomic) id <DoSomethingDelegate> delegate;
In the updating class .m
-(void)doSomethingSomewhereElse {
if (self.delegate != nil && [self.delegate respondsToSelector:#selector(doSomething)]) {
[self.delegate performSelector:#selector(doSomething)];
}
} else {
NSLog(#"Delgate doesn't implement doSomething");
}
}
In the receiving class' .h:
Conform to protocol <DoSomethingDelegate>
#interface myDoSomethingClass : NSObject <DoSomethingDelegate>
...
Implement the delegate method in the receiving class' .m:
-(void)someInit{
//set the delegate to self
}
In the view controller .m
-(void)doSomething{
NSLog(#"The delegate told me to do this!");
}
The deck is not its own delegate. Right now your code says that a Deck is a SpeedSliderDelegate, and that a Deck's delegate is a DeckLooperDelegate.
If you always need a delegate for Deck, you can do it this way:
- (id) initWithDelegate:(id<DeckLooperDelegate>)delegate {
if (self = [super init]) {
self.delegate = delegate;
cards = [[NSMutableArray alloc] init];
NSInteger aCount, picNum = 0;
// etc etc etc
}
}
Then, in the DeckLooperDelegate that creates the deck, you call it like this:
Deck *deck = [[Deck alloc] initWithDelegate:self];
Then you want your speed slider to set the deck as its delegate.
mySpeedSlider.delegate = deck;
Now mySpeedSlider can call [delegate setSpeed:] to change the deck's speed.

I can not figure out how to resolve SIGABRT error in Xcode

I am working on a basic calculator app, following a tutorial for an iTunes U class. I thought I had worked it out perfectly but when I go to run the application in the simulator, I get an unexpected error. The calculator works by entering the number, pressing the enter button, entering the second number, then the enter button and then the operation. It allows me to append digits to form a multi-digit number, but as soon as I press "enter" it quits out and says "Thread 1: Program received signal: "SIGABRT."" I have double and triple checked my code and cannot seem to find anything wrong, so i thought i would post it all on here and see if you guys can figure it out. Thanks in advance!
CalculatorBrain.h
#import <Foundation/Foundation.h>
#interface CalculatorBrain : NSObject
- (void)pushOperand:(double)operand;
- (double)performOperation:(NSString *)operation;
#end
CalculatorBrain.m
#import "CalculatorBrain.h"
#interface CalculatorBrain()
#property (nonatomic, strong) NSMutableArray *operandStack;
#end
#implementation CalculatorBrain
#synthesize operandStack = _operandStack;
- (NSMutableArray *)operandStack
{
if (!_operandStack) {
_operandStack = [[NSMutableArray alloc] init];
}
return _operandStack;
}
- (void)pushOperand:(double)operand
{
NSNumber *operandObject = [NSNumber numberWithDouble:operand];
[self.operandStack addObject:operandObject];
}
- (double)popOperand
{
NSNumber *operandObject = [self.operandStack lastObject];
if (operandObject) [self.operandStack removeLastObject];
return [operandObject doubleValue];
}
- (double)performOperation:(NSString *)operation
{
double result = 0;
if ([operation isEqualToString:#"+"]){
result = [self popOperand] + [self popOperand];
} else if ([#"*" isEqualToString:operation]) {
result = [self popOperand] * [self popOperand];
} else if ([operation isEqualToString:#"-"]) {
double subtrahend = [self popOperand];
result = [self popOperand] - subtrahend;
} else if ([operation isEqualToString:#"/"]) {
double divisor = [self popOperand];
if (divisor) result = [self popOperand] / divisor;
}
[self pushOperand:result];
return result;
}
#end
CalculatorViewController.h
#import <UIKit/UIKit.h>
#interface CalculatorViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *display;
#end
CalculatorViewController.m
#import "CalculatorViewController.h"
#import "CalculatorBrain.h"
#interface CalculatorViewController()
#property (nonatomic) BOOL userIsInTheMiddleOfEnteringANumber;
#property (nonatomic, strong) CalculatorBrain *brain;
#end
#implementation CalculatorViewController
#synthesize display;
#synthesize userIsInTheMiddleOfEnteringANumber;
#synthesize brain = _brain;
- (CalculatorBrain *)brain
{
if(!_brain) _brain = [[CalculatorBrain alloc] init];
return _brain;
}
- (IBAction)digitPressed:(UIButton *)sender {
NSString *digit = [sender currentTitle];
if (self.userIsInTheMiddleOfEnteringANumber) {
self.display.text = [self.display.text stringByAppendingString:digit];
} else {
self.display.text = digit;
self.userIsInTheMiddleOfEnteringANumber = YES;
}
}
- (IBAction)enterPressed
{
[self.brain pushOperand:[self.display.text doubleValue]];
self.userIsInTheMiddleOfEnteringANumber = NO;
}
- (IBAction)operationPressed:(UIButton *)sender
{
if (self.userIsInTheMiddleOfEnteringANumber) {
[self enterPressed];
}
NSString *operation = [sender currentTitle];
double result = [self.brain performOperation:operation];
self.display.text = [NSString stringWithFormat:#"%g", result];
}
#end
Open CalculatorViewController.xib file in Xcode and right-click the "File's Owner".
Check the appearing pop-up if you have any linked properties listed that are not implemented in the CalculatorViewController.h file (according to the above posted code, the only properties linked from .xib to .h should be a UILabel called "display". Delete all invalid linked properties, if any is available (invalid linked properties would be marked with a yellow warning sign).
Expand your project Executable and right click on it. and click on GetInfo->Argument tag aat end of the window you see plus and minus sign button click on + sighn button and write
Name Value
NSZombieEnabled YES
then after execute your project and whenever crash your application click on run munu-> console you see there why your application crash. please try this may be this will help you.

How to store the values which are entered in different text fields to the Server in objective C

How to store the values which are entered in different text fields to the Server in objective C, In my project i have created the a form where it consists of different text fields where the user has to enter the values to the text field, i have kept one SAVE button, where after entering the values to the text field the user has to click the Save button.
I have to save the values entered in the text fields to the server on the click of the SAVE Button.
So how to save the data or values to the server on the click of the SAVE button.
The Following is the code i have used to create the form,
In .h File :
#import <UIKit/UIKit.h>
#import "PickerViewController.h"
#interface PopAppViewController : UIViewController < NumberPickedDelegate>{
UIPopoverController *popOverController;
UIPopoverController *popOverControllerWithPicker;
PickerViewController *pickerViewController;
IBOutlet UITextField *txtTest;
IBOutlet UITextField *txtSun;
IBOutlet UITextField *txtMon;
IBOutlet UITextField *txtTue;
IBOutlet UITextField *txtWed;
IBOutlet UITextField *txtThurs;
IBOutlet UITextField *txtFri;
IBOutlet UITextField *txtSat;
IBOutlet UITextField *txtTotal;
IBOutlet UITextField *txtTask;
IBOutlet UITextField *txtProject;
}
#property (nonatomic, retain) UIPopoverController *popOverController;
#property (nonatomic, retain) UIPopoverController *popOverControllerWithPicker;
#property (nonatomic, retain) PickerViewController *pickerViewController;
#property (nonatomic, retain) UITextField *txtTest;
#property (nonatomic, retain) UITextField *txtSun;
#property (nonatomic, retain) UITextField *txtMon;
#property (nonatomic, retain) UITextField *txtTue;
#property (nonatomic, retain) UITextField *txtWed;
#property (nonatomic, retain) UITextField *txtThurs;
#property (nonatomic, retain) UITextField *txtFri;
#property (nonatomic, retain) UITextField *txtSat;
#property (nonatomic, retain) UITextField *txtTotal;
#property (nonatomic, retain) UITextField *txtTask;
#property (nonatomic, retain) UITextField *txtProject;
-(IBAction)displayPickerPopover;
-(IBAction)exit;
-(IBAction)reset;
-(IBAction)save;
-(IBAction)total;
#end
In .m file :
#import "PopAppViewController.h"
//#import "TimeSheetDatabase.h"
#implementation PopAppViewController
#synthesize popOverController,popOverControllerWithPicker,pickerViewController,txtTest,txtSun,txtMon,txtTue,txtWed,txtThurs,txtFri,txtSat,txtTotal,txtTask,txtProject;
//-(id)initWithtxtProject:(NSString *)txtProject txtTask:(NSString *)txtTask txtSun:(int)txtSun txtMon:(int)txtMon txtTue:(int)txtTue txtWed:(int)txtWed txtThurs:(int)txtThurs txtFri:(int)txtFri txtSat:(int)txtSat txtTotal:(int)txtTotal{
//
// self=[super init];
// if(self){
// self.txtProject = txtProject;
// self.txtTask = txtTask;
// self.txtSun = txtSun;
// self.txtMon = txtMon;
// self.txtTue = txtTue;
// self.txtWed = txtWed;
// self.txtThurs = txtThurs;
// self.txtFri = txtFri;
// self.txtSat = txtSat;
// self.txtTotal = txtTotal;
//
// }
//}
-(IBAction)displayPickerPopover {
[txtTest resignFirstResponder];
CGSize sizeOfPopover = CGSizeMake(300, 422);
CGPoint positionOfPopover = CGPointMake(32, 325);
[popOverControllerWithPicker presentPopoverFromRect:CGRectMake(positionOfPopover.x, positionOfPopover.y, sizeOfPopover.width, sizeOfPopover.height)
inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
-(IBAction)exit{
exit(0);
}
-(IBAction)reset{
txtSun.text = #"";
txtMon.text = #"";
txtTue.text = #"";
txtWed.text = #"";
txtThurs.text = #"";
txtFri.text = #"";
txtSat.text = #"";
txtTotal.text = #"";
txtTest.text = #"";
txtTask.text = #"";
}
-(IBAction)save{
}
-(IBAction)total{
int result = [txtSun.text intValue] + [txtMon.text intValue] + [txtTue.text intValue] + [txtWed.text intValue] + [txtThurs.text intValue] + [txtFri.text intValue] + [txtSat.text intValue];
txtTotal.text = [NSString stringWithFormat:#"%d",result];
}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
-(void)numberDidChangeTo:(NSString *)newNumber {
txtTest.text = newNumber;
}
-(void)didChangeSelection:(NSString *)newValue {
txtTest.text = newValue;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
pickerViewController = [[PickerViewController alloc] init];
pickerViewController.delegate = self;
popOverControllerWithPicker = [[UIPopoverController alloc] initWithContentViewController:pickerViewController];
popOverController.popoverContentSize = CGSizeMake(300, 216);
// NSArray *timesheetinfo = [[TimeSheetDatabase database]getAllTimeSheet];
// for(timesheetinfo *info in timesheetinfo){
//
// NSLog(#"%# - %# ",info.project,info.task);
// }
[super viewDidLoad];
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
- (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)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[popOverController release];
[popOverControllerWithPicker release];
[pickerViewController release];
[txtTest release];
[super dealloc];
}
#end
You need to compile the data into a JSON string, and then send it to the server with an NSURLRequest
-(IBAction)save
{
// build JSON string
NSDictionary *postDictionary = [NSDictionary dictionaryWithObjectsAndKeys:self.txtTest.text, #"test",
self.txtSun.text, #"sun",
self.txtSun.text, #"mon",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:postDictionary options:NSJSONWritingPrettyPrinted error:NULL];
// perform http request (on a background thread)
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:#"http://example.com/save.php" cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSHTTPURLResponse *urlResponse = nil;
NSError *error = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
// and now go back to the main thread
dispatch_async(dispatch_get_main_queue(), ^{
NSAutoreleasePool *mainQueuePool = [[NSAutoreleasePool alloc] init];
// debug: print response
NSLog(#"%#", [[NSString alloc] initWithData:responseData encoding:NSISOLatin1StringEncoding]);
// check for http error (this includes php exceptions)
if ([urlResponse statusCode] != 200) {
NSLog(#"save failed with status code != 200");
return;
}
[mainQueuePool release];
});
[pool release];
});
}
And in your php:
$rawData = file_get_contents("php://input");
$postData = json_decode($rawData);
print_r($postData);
As Objective-C supports pure C, you could use a C library like described here to connect to a MySQL Server.