uiimageview.image not always changing when game over - ios

Hi iam really new to coding and to start of i am making a really simple game in Xcode. The game is done but i do have a little problem. rarely at times when in game over pig.image does not change and the previous animation keeps on going even after [pig stopAnimation]... heres the code from when you get game over to where the image should change.....
-(void)gameover1{
[jetpacksound stop];
[self hitsound];
[pig stopAnimating];
[movementtimer invalidate];
if (score > highscorenumber) {
highscorenumber = score;
[[NSUserDefaults standardUserDefaults] setInteger:highscorenumber forKey:#"highscoresaved"];
}
else{
highscore.text = [NSString stringWithFormat:#"Try Harder Next Time"];
}
movementtimer = [NSTimer scheduledTimerWithTimeInterval:.035 target:self selector:#selector(gameover1movement) userInfo:nil repeats:YES];
bam.hidden = NO;
flash.hidden = NO;
background1.hidden = YES;
background2.hidden = YES;
background3.hidden = YES;
pauseg.hidden = YES;
scorelabel.hidden = YES;
fork1.hidden = YES;
fork2.hidden = YES;
fork3.hidden = YES;
fork4.hidden = YES;
knife1.hidden = YES;
knife2.hidden = YES;
knife3.hidden = YES;
knife4.hidden = YES;
poisoncloud.hidden = YES;
cake.hidden = YES;
}
-(void)gameover1movement{
pig.center = CGPointMake(pig.center.x, pig.center.y - 30);
if (IS_IPAD)
{
//do stuff for iPad
if (pig.center.y < 400) {
[self gameover2];
}
}
else
{
if(IS_IPHONE_5)
{
//do stuff for 4 inch iPhone screen
if (pig.center.y < 200) {
[self gameover2];
}
}
else
{
//do stuff for 3.5 inch iPhone screen
}
}
}
-(void)gameover2{
[movementtimer invalidate];
movementtimer = [NSTimer scheduledTimerWithTimeInterval:.035 target:self selector:#selector(gameover2movement) userInfo:nil repeats:YES];
pig.image = [UIImage imageNamed:#"DeadPig.png"];
background1.hidden = NO;
background2.hidden = NO;
background3.hidden = NO;
bam.hidden = YES;
flash.hidden = YES;
if (IS_IPAD)
{
//do stuff for iPad
pig.frame = CGRectMake(pig.center.x - 115, pig.center.y - 165, 230.0f, 330.0f);
if (pig.center.x < 115) {
pig.center = CGPointMake(115, pig.center.y);
}
if (pig.center.x > 653) {
pig.center = CGPointMake(653, pig.center.y);
}
background3.center = CGPointMake(384, 512);
background2.center = CGPointMake(384, 1536);
background1.center = CGPointMake(384, 2560);
}
else
{
if(IS_IPHONE_5)
{
//do stuff for 4 inch iPhone screen
pig.frame = CGRectMake(pig.center.x - 50, pig.center.y - 75, 100.0f, 150.0f);
if (pig.center.x < 50) {
pig.center = CGPointMake(50, pig.center.y);
}
if (pig.center.x > 270) {
pig.center = CGPointMake(270, pig.center.y);
}
background3.center = CGPointMake(160, 284);
background2.center = CGPointMake(160, 852);
background1.center = CGPointMake(160, 1420);
}
else
{
//do stuff for 3.5 inch iPhone screen
}
}
}

Related

how to display the congratulation view in iPhone using objective -c

I am developing a learning app for preschool kids. This is my code:
numbersStoreArray = [[NSMutableArray alloc]initWithObjects:#"1.png",#"2.png",#"3.png",#"4.png",#"5.png",#"6.png",#"7.png",#"8.png",#"9.png",#"10.png", nil];
commonFunctionObject = [[SpeechCommonFunctions alloc]init];
commonFunctionObject.isRecordComplete = NO;
counter = 0;
isMicPresent = YES;
_confirmationPopupView.hidden = true;
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:#selector(repeatActionFire) userInfo:nil repeats:NO];
}
-(void)repeatActionFire
{
if(counter >= numbersStoreArray.count)
{
NSLog(#"finished");
[_numbersShowImageView removeFromSuperview];
[_speakerOrMicImageView removeFromSuperview];
UIImageView *congratzView = [[UIImageView alloc]initWithFrame:self.view.frame];
congratzView.image = [UIImage imageNamed:#""];
[self.view addSubview:congratzView];
}
else
{
[commonFunctionObject textToSpeechAction:numbersStoreArray :counter :_numbersShowImageView :_speakerOrMicImageView :isMicPresent];
[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(ActionToCkeckRecordCompletion) userInfo:nil repeats:YES];
}
}
-(void)ActionToCkeckRecordCompletion
{
if(commonFunctionObject.isRecordComplete)
{
_confirmationPopupView.hidden = false;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)playButtonAction:(id)sender
{
[commonFunctionObject recordPlayAction];
}
- (IBAction)nextButtonAction:(id)sender
{
counter+=1;
_confirmationPopupView.hidden = true;
commonFunctionObject.isRecordComplete = NO;
if(commonFunctionObject.player.playing){[commonFunctionObject.player stop];}
[self repeatActionFire];
}
- (IBAction)retryButtonAction:(id)sender
{
_confirmationPopupView.hidden = true;
commonFunctionObject.isRecordComplete = NO;
if(commonFunctionObject.player.playing){[commonFunctionObject.player stop];}
[self repeatActionFire];
}
After completion of this, this entry to the repeatActionFire and show finished. My question is: I need to display the congratulation view after the completion of the game and need to use two buttons.
Buttons for:
to reach the homepage
to retry the game.
How to do this?

Expected identifier on if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)

*This is the whole code :)
I have been trying to fix this for an hour now, but i can still not make it.
I would be happy if someone could help me :)
Still can't make the UI_USER_INTERFACE_IDIOM code work.*
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
-(void)Collision{
if (CGRectIntersectsRect(Heli.frame, Obstacle.frame)) {
[self EndGame];
}
if (CGRectIntersectsRect(Heli.frame, Obstacle2.frame)) {
[self EndGame];
}
if (CGRectIntersectsRect(Heli.frame, Bottom1.frame)) {
[self EndGame];
}
if (CGRectIntersectsRect(Heli.frame, Top1.frame)) {
[self EndGame];
}
}
-(void)EndGame{
if (Scorenumber > HighScore) {
HighScore = Scorenumber;
[[NSUserDefaults standardUserDefaults] setInteger:HighScore
forKey:#"HighScoreSaved"];
}
Heli.hidden = YES;
[timer invalidate];
[Scorer invalidate];
[self performSelector:#selector(NewGame) withObject: nil afterDelay:2];
}
-(void)NewGame{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
// For iPhone
Bottom1.hidden = YES;
Top1.hidden = YES;
Obstacle.hidden = YES;
Obstacle2.hidden = YES;
corona.hidden = YES;
Intro1.hidden = NO;
Intro2.hidden = NO;
Intro3.hidden = NO;
Heli.hidden = NO;
Heli.center = CGPointMake(88, 286);
Heli.image = [UIImage imageNamed:#"buss til app opp.png"];
Start = YES;
Scorenumber = 0;
Score.text = [NSString stringWithFormat:#"Score: 0"];
Intro3.text = [NSString stringWithFormat:#"HighScore: %i", HighScore];
}
} else{
// For iPad
Bottom1.hidden = YES;
Top1.hidden = YES;
Obstacle.hidden = YES;
Obstacle2.hidden = YES;
corona.hidden = YES;
Intro1.hidden = NO;
Intro2.hidden = NO;
Intro3.hidden = NO;
Heli.hidden = NO;
Heli.center = CGPointMake(153, 515);
Heli.image = [UIImage imageNamed:#"buss til app opp.png"];
Start = YES;
Scorenumber = 0;
Score.text = [NSString stringWithFormat:#"Score: 0"];
Intro3.text = [NSString stringWithFormat:#"HighScore: %i", HighScore];
Just look at following code:
-(void)NewGame{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
// For iPhone
Bottom1.hidden = YES;
Top1.hidden = YES;
Obstacle.hidden = YES;
Obstacle2.hidden = YES;
corona.hidden = YES;
Intro1.hidden = NO;
Intro2.hidden = NO;
Intro3.hidden = NO;
Heli.hidden = NO;
Heli.center = CGPointMake(88, 286);
Heli.image = [UIImage imageNamed:#"buss til app opp.png"];
Start = YES;
Scorenumber = 0;
Score.text = [NSString stringWithFormat:#"Score: 0"];
Intro3.text = [NSString stringWithFormat:#"HighScore: %i", HighScore];
}
} else{
and see - "}" symbol on line before "} else{" is wrong. It is the pair for
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
opening construction, so "else" is "standalone - it is wrong.
Try to delete this "}".

Unable to hear sound in iOS

In my app I've having trouble to hear a sound. In particular this is my code:
#import <QuartzCore/QuartzCore.h>
#import <AudioToolbox/AudioToolbox.h>
#import "ViewController.h"
#import "RIOInterface.h"
#import "KeyHelper.h"
#import "Toast+UIView.h"
#interface ViewController () {
BOOL watermarkReceived;
float frequencyRecived;
CABasicAnimation *theAnimation;
BOOL water1, water2, water3, water4, noWater;
}
#property(nonatomic)NSTimer *timer, *timer2;
#property(nonatomic,strong)AVAudioPlayer *player;
#property(nonatomic,strong)NSURL *url;
#end
#implementation ViewController
#synthesize isListening;
#synthesize rioRef;
#synthesize currentFrequency;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//self.labelPosition.font=[UIFont fontWithName:#"DBLCDTempBlack" size:20.0];
NSError *error;
self.url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"sms_alert_circles" ofType:#"mp3"]];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.url error:&error];
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
[session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&setCategoryError];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
self.rioRef = [RIOInterface sharedInstance];
[rioRef setSampleRate:44100];
[rioRef setFrequency:394];//294
[rioRef initializeAudioSession];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)startListenWatermark:(UIButton *)sender {
if ([sender isSelected]) {
[self stopListener];
[UIApplication sharedApplication].idleTimerDisabled = NO;
[sender setSelected:NO];
[self.imageListening.layer removeAllAnimations];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
//self.labelPosition.font=[UIFont fontWithName:#"DBLCDTempBlack" size:20.0];
self.labelPosition.text = #"Nessuna postazione";
} else {
water1 = water2 = water3 = water4 = NO;
[self startListener];
[UIApplication sharedApplication].idleTimerDisabled = YES;
[sender setSelected:YES];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
self.labelPosition.text = #"Nessuna postazione";
theAnimation = [CABasicAnimation animationWithKeyPath:#"opacity"];
theAnimation.duration = 0.4;
theAnimation.repeatDuration = 10000;
theAnimation.autoreverses = YES;
theAnimation.delegate = self;
theAnimation.fromValue = [NSNumber numberWithFloat:1.0];
theAnimation.toValue = [NSNumber numberWithFloat:0.1];
[self.imageListening.layer addAnimation:theAnimation forKey:#"animateOpacity"];
}
}
#pragma mark Listener methods
- (void)startListener {
[self.rioRef startListening:self];
}
- (void)stopListener {
[self.rioRef stopListening];
}
- (void)frequencyChangedWithValue:(float)newFrequency {
frequencyRecived = newFrequency;
watermarkReceived = YES;
if (frequencyRecived > 18000) {
if (frequencyRecived >= 18000 && frequencyRecived <= 18110 && !water1) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"1" waitUntilDone:YES];
water2 = water3 = water4 = NO;
water1 = YES;
noWater = YES;
}
if (frequencyRecived >= 18115 && frequencyRecived <= 18250 && !water2) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"2" waitUntilDone:YES];
water1 = water3 = water4 = NO;
water2 = YES;
noWater = YES;
}
if (frequencyRecived >= 18255 && frequencyRecived <= 18440 && !water3) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"3" waitUntilDone:YES];
water1 = water2 = water4 = NO;
water3 = YES;
noWater = YES;
}
if (frequencyRecived >= 18445 && !water4) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"4" waitUntilDone:YES];
water1 = water2 = water3 = NO;
water4 = YES;
noWater = YES;
}
} else {
if (noWater) {
[self performSelectorOnMainThread:#selector(noWatermark) withObject:nil waitUntilDone:YES];
noWater = NO;
}
}
}
- (void)noWatermark {
self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(noPosition:) userInfo:nil repeats:NO];
}
- (void)noPosition:(NSTimer*)aTimer {
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"Nessuna postazione" waitUntilDone:YES];
[self performSelectorInBackground:#selector(redLed) withObject:nil];
self.timer2 = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(resetFlags) userInfo:nil repeats:NO];
}
- (void)resetFlags {
water1 = water2 = water3 = water4 = NO;
}
- (void)redLed {
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
}
- (void)setTextInLabel:(NSString*)position {
[self.timer invalidate];
self.timer = nil;
if ([position isEqualToString:#"Nessuna postazione"]) {
self.labelPosition.text = position;
}
self.labelPosition.text = position;
if (![position isEqualToString:#"Nessuna postazione"]) {
[self.player setVolume:1.0];
[self.player prepareToPlay];
[self.player play];
NSString *textForToast = [NSString stringWithFormat:#"Postazione %#", position];
UIImage *image = [[UIImage alloc]init];
if ([position isEqualToString:#"1"]) {
image = [UIImage imageNamed:#"image_smart.png"];
}
if ([position isEqualToString:#"2"]) {
image = [UIImage imageNamed:#"image_500.png"];
}
if ([position isEqualToString:#"3"]) {
image = [UIImage imageNamed:#"image_mini.png"];
}
if ([position isEqualToString:#"4"]) {
image = [UIImage imageNamed:#"image_aygo.png"];
}
[self.view makeToast:textForToast duration:5.0 position:#"bottom" title:#"Watermark ricevuto" image:image];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_green.png"]];
}
}
#end
In particular, this class should hear (with microphone) an audio signal in which there are some tone with a frequency >= 18000 Hz. So I will make this: when it recognize a tone of a frequency >= 18000 Hz it should play a sound.
When I try to run the app on the device I hear the sound with a very low volume by using iPhone speaker, but when I plug the headphone I hear the sound with an high volume. I tried to run the app by using simulator and when I use simulator it works nice. Why's that? Can you help me to fix this class?
PS: to detect the frequency of sounds I'm using pitch detector.
I solved it, I post here the code:
#import <QuartzCore/QuartzCore.h>
#import <AudioToolbox/AudioToolbox.h>
#import "ViewController.h"
#import "RIOInterface.h"
#import "KeyHelper.h"
#import "Toast+UIView.h"
#interface ViewController () {
BOOL watermarkReceived;
float frequencyRecived;
CABasicAnimation *theAnimation;
BOOL water1, water2, water3, water4, noWater;
}
#property(nonatomic)NSTimer *timer, *timer2;
//#property(strong)AVAudioPlayer *player;
#property(nonatomic,strong)NSURL *url;
#end
#implementation ViewController
#synthesize isListening;
#synthesize rioRef;
#synthesize currentFrequency;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// NSError *error;
//
// self.url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"sms_alert_circles" ofType:#"mp3"]];
// player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.url error:&error];
//
// AVAudioSession *session = [AVAudioSession sharedInstance];
//
// NSError *setCategoryError = nil;
// [session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&setCategoryError];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
self.rioRef = [RIOInterface sharedInstance];
[rioRef setSampleRate:44100];
[rioRef setFrequency:394];//294
[rioRef initializeAudioSession];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)startListenWatermark:(UIButton *)sender {
if ([sender isSelected]) {
[self stopListener];
[UIApplication sharedApplication].idleTimerDisabled = NO;
[sender setSelected:NO];
[self.imageListening.layer removeAllAnimations];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
//self.labelPosition.font=[UIFont fontWithName:#"DBLCDTempBlack" size:20.0];
self.labelPosition.text = #"Nessuna postazione";
} else {
water1 = water2 = water3 = water4 = NO;
[self startListener];
[UIApplication sharedApplication].idleTimerDisabled = YES;
[sender setSelected:YES];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
self.labelPosition.text = #"Nessuna postazione";
theAnimation = [CABasicAnimation animationWithKeyPath:#"opacity"];
theAnimation.duration = 0.4;
theAnimation.repeatDuration = 10000;
theAnimation.autoreverses = YES;
theAnimation.delegate = self;
theAnimation.fromValue = [NSNumber numberWithFloat:1.0];
theAnimation.toValue = [NSNumber numberWithFloat:0.1];
[self.imageListening.layer addAnimation:theAnimation forKey:#"animateOpacity"];
}
}
#pragma mark Listener methods
- (void)startListener {
[self.rioRef startListening:self];
}
- (void)stopListener {
[self.rioRef stopListening];
}
- (void)frequencyChangedWithValue:(float)newFrequency {
frequencyRecived = newFrequency;
watermarkReceived = YES;
if (frequencyRecived > 18000) {
if (frequencyRecived >= 18000 && frequencyRecived <= 18110 && !water1) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"1" waitUntilDone:YES];
water2 = water3 = water4 = NO;
water1 = YES;
noWater = YES;
}
if (frequencyRecived >= 18115 && frequencyRecived <= 18250 && !water2) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"2" waitUntilDone:YES];
water1 = water3 = water4 = NO;
water2 = YES;
noWater = YES;
}
if (frequencyRecived >= 18255 && frequencyRecived <= 18440 && !water3) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"3" waitUntilDone:YES];
water1 = water2 = water4 = NO;
water3 = YES;
noWater = YES;
}
if (frequencyRecived >= 18445 && !water4) {
[self.timer invalidate];
self.timer = nil;
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"4" waitUntilDone:YES];
water1 = water2 = water3 = NO;
water4 = YES;
noWater = YES;
}
} else {
if (noWater) {
[self performSelectorOnMainThread:#selector(noWatermark) withObject:nil waitUntilDone:YES];
noWater = NO;
}
}
}
- (void)noWatermark {
self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(noPosition:) userInfo:nil repeats:NO];
}
- (void)noPosition:(NSTimer*)aTimer {
[self performSelectorOnMainThread:#selector(setTextInLabel:) withObject:#"Nessuna postazione" waitUntilDone:YES];
[self performSelectorInBackground:#selector(redLed) withObject:nil];
self.timer2 = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:#selector(resetFlags) userInfo:nil repeats:NO];
}
- (void)resetFlags {
water1 = water2 = water3 = water4 = NO;
}
- (void)redLed {
[self.imageLed setImage:[UIImage imageNamed:#"image_led_red.png"]];
}
- (void)setTextInLabel:(NSString*)position {
[self.timer invalidate];
self.timer = nil;
NSError *error;
self.url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:#"sms_alert_circles" ofType:#"mp3"]];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.url error:&error];
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
[session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&setCategoryError];
if ([position isEqualToString:#"Nessuna postazione"]) {
self.labelPosition.text = position;
}
self.labelPosition.text = position;
if (![position isEqualToString:#"Nessuna postazione"]) {
[player setVolume:1.0];
[player prepareToPlay];
[player play];
NSString *textForToast = [NSString stringWithFormat:#"Postazione %#", position];
UIImage *image = [[UIImage alloc]init];
if ([position isEqualToString:#"1"]) {
image = [UIImage imageNamed:#"image_smart.png"];
}
if ([position isEqualToString:#"2"]) {
image = [UIImage imageNamed:#"image_500.png"];
}
if ([position isEqualToString:#"3"]) {
image = [UIImage imageNamed:#"image_mini.png"];
}
if ([position isEqualToString:#"4"]) {
image = [UIImage imageNamed:#"image_aygo.png"];
}
[self.view makeToast:textForToast duration:5.0 position:#"bottom" title:#"Watermark ricevuto" image:image];
[self.imageLed setImage:[UIImage imageNamed:#"image_led_green.png"]];
}
}
#end
I just put the initializer of the AVAudioPlayer into method setTextInLabel and it works.
Thank you!

Quiz app -next to display after Image result hides

I am new to App Development, sorry if I am asking silly questions :(
I am developing a Quiz App. Whenever I give a right or wrong answer, an image appears with right or wrong answer result, however it stays for a few seconds, but after that - it does not continue with the next question. It just shows my background images with buttons. How can I set a code, that it goes straight to a new question, when the result image is gone.
I will be very thankful for your help.
I just want that after the Result-image closes, the quiz continues with the next question.
This is the code i have setup in Game.m file.
-(void)RightAnswer{
ScoreNumber = ScoreNumber + 1;
Score.text = [NSString stringWithFormat:#"%i", ScoreNumber];
Answer1.hidden = YES;
Answer2.hidden = YES;
Answer3.hidden = YES;
CategorySelected.hidden = NO;
Next.hidden = NO;
imageQuestion.hidden = YES;
Results.hidden = NO;
Results.image = [UIImage imageNamed:#"right.png"]; [self performSelector:#selector(Results) withObject:nil afterDelay:2.0];
GameInProgress = YES;
}
-(void)WrongAnswer{
LivesNumber = LivesNumber - 1;
Lives.text = [NSString stringWithFormat:#"%i", LivesNumber];
Answer1.hidden = YES;
Answer2.hidden = YES;
Answer3.hidden = YES;
imageQuestion.hidden = YES;
CategorySelected.hidden = NO;
Next.hidden = NO;
Results.hidden = NO;
Results.image = [UIImage imageNamed:#"wrong.png"];[self performSelector:#selector(Results) withObject:nil afterDelay:2.0];
GameInProgress = YES;
if(LivesNumber ==0) {
Results.image = [UIImage imageNamed:#"gameover.png"];
GameInProgress = NO;
Exit.hidden = NO;
}
-(void)RightAnswer{
ScoreNumber = ScoreNumber + 1;
Score.text = [NSString stringWithFormat:#"%i", ScoreNumber];
Answer1.hidden = YES;
Answer2.hidden = YES;
Answer3.hidden = YES;
Answer1Correct ==YES;
CategorySelected.hidden = NO;
Next.hidden = NO;
imageQuestion.hidden = YES;
Results.hidden = NO;
Results.image = [UIImage imageNamed:#"right.png"]; [self performSelector:#selector(Results) withObject:nil afterDelay:2.0];
GameInProgress = YES;
}
I think the issue is that you never set Answer1Correct to anything. so if you add Answer1Correct ==YES to the correct answer method and Answer1Correct ==NO to the wrong method then it should work
-(void)Results{ // just change formate of answer.
Results.hidden = YES;
}
-(IBAction)Answer1: (id) sender{
if (Answer1Correct ==YES) {
[self RightAnswer];
}else{
[self WrongAnswer];
}
}
-(IBAction)Answer2: (id) sender{
if (Answer2Correct ==YES) {
[self RightAnswer];
}
else{
[self WrongAnswer];
}
}
-(IBAction)Answer3: (id) sender{
if (Answer3Correct ==YES) {
[self RightAnswer];
}
else{
[self WrongAnswer];
}
}
i may be wrong here but I think you need an if to the else.
But I could be wrong.
if(LivesNumber ==0) {
Results.image = [UIImage imageNamed:#"gameover.png"];
GameInProgress = NO;
Exit.hidden = NO;
}else{
donextcard();
}
if you want to know how to make that function we would need to see more of the code.

Problems with view controllers going into the background of UITabBarController

I have a UITabBarController with 3 view controllers connected to it. Everything works fine apart from when you switch from one view to another, the new view takes a moment to reload what it was doing. I know this isn't such a big deal but it just makes the app look a bit sloppy. Does anyone know how I can keep the app running in the background, or something so that it doesn't have to reload each time.
As you might have noticed I'm very new to Objective-C so I can understand if I'm being unclear but any help is really appreciated!
EDIT: FOR DAVID
This is the code for the stopwatch in the .m file:
#implementation StopwatchViewController
- (BOOL)prefersStatusBarHidden
{
return YES;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
isCounting = false;
}
- (IBAction)startOrStop:(id)sender
{
if (self->isCounting == false) {
self->isCounting = true;
[self startStopwatch];
} else {
self->isCounting = false;
[self stopStopwatch];
}
}
- (void)startStopwatch
{
[startStopButton setTitle:#"STOP" forState:UIControlStateNormal];
[self performSelector:#selector(stopwatch) withObject:self afterDelay:1.0];
}
- (IBAction)resetStopwatch:(id)sender
{
[self reset];
}
- (void)stopwatch
{
if (self->isCounting == false) {
return;
} else {
NSInteger hourInt = [hourLabel.text intValue];
NSInteger minuteInt = [minuteLabel.text intValue];
NSInteger secondInt = [secondLabel.text intValue];
if (secondInt == 59) {
secondInt = 0;
if (minuteInt == 59) {
minuteInt = 0;
if (hourInt == 23) {
hourInt = 0;
} else {
hourInt += 1;
}
} else {
minuteInt += 1;
}
} else {
secondInt += 1;
}
NSString *hourString = [NSString stringWithFormat:#"%02d", hourInt];
NSString *minuteString = [NSString stringWithFormat:#"%02d", minuteInt];
NSString *secondString = [NSString stringWithFormat:#"%02d", secondInt];
hourLabel.text = hourString;
minuteLabel.text = minuteString;
secondLabel.text = secondString;
CGRect hourFrame = self->hourBar.frame;
CGRect minuteFrame = self->minuteBar.frame;
CGRect secondFrame = self->secondBar.frame;
if ((NSInteger)hourFrame.size.height != hourInt) { // check if we need to modify
hourFrame.origin.y -= ((hourInt * 10.0) - hourFrame.size.height);
hourFrame.size.height = (hourInt * 10.0);
self->hourBar.frame = hourFrame;
}
if ((NSInteger)minuteFrame.size.height != minuteInt) { // check if we need to modify
minuteFrame.origin.y -= ((minuteInt * 4.0) - minuteFrame.size.height);
minuteFrame.size.height = (minuteInt * 4.0);
self->minuteBar.frame = minuteFrame;
}
if ((NSInteger)secondFrame.size.height != secondInt) { // check if we need to modify
secondFrame.origin.y -= ((secondInt * 4.0) - secondFrame.size.height);
secondFrame.size.height = (secondInt * 4.0);
self->secondBar.frame = secondFrame;
}
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(stopwatch) userInfo:nil repeats:NO];
}
}
- (void)stopStopwatch
{
[startStopButton setTitle:#"START" forState:UIControlStateNormal];
}
- (void)reset
{
[startStopButton setTitle:#"START" forState:UIControlStateNormal];
self->isCounting = false;
hourLabel.text = #"00";
minuteLabel.text = #"00";
secondLabel.text = #"00";
CGRect hourFrame = self->hourBar.frame;
CGRect minuteFrame = self->minuteBar.frame;
CGRect secondFrame = self->secondBar.frame;
hourFrame.size.height = 0;
minuteFrame.size.height = 0;
secondFrame.size.height = 0;
hourFrame.origin.y = 321.0;
minuteFrame.origin.y = 321.0;
secondFrame.origin.y = 321.0;
self->hourBar.frame = hourFrame;
self->minuteBar.frame = minuteFrame;
self->secondBar.frame = secondFrame;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
SECOND EDIT FOR DAVID:
Changed the main parts of the code to look like this:
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:YES];
[self swapFrames];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
[self updateBars];
}
- (void)stopwatch
{
if (self->isCounting == false) {
return;
} else {
hourInt = [hourLabel.text intValue];
minuteInt = [minuteLabel.text intValue];
secondInt = [secondLabel.text intValue];
if (secondInt == 59) {
secondInt = 0;
if (minuteInt == 59) {
minuteInt = 0;
if (hourInt == 23) {
hourInt = 0;
} else {
hourInt += 1;
}
} else {
minuteInt += 1;
}
} else {
secondInt += 1;
}
NSString *hourString = [NSString stringWithFormat:#"%02d", hourInt];
NSString *minuteString = [NSString stringWithFormat:#"%02d", minuteInt];
NSString *secondString = [NSString stringWithFormat:#"%02d", secondInt];
hourLabel.text = hourString;
minuteLabel.text = minuteString;
secondLabel.text = secondString;
[self swapFrames];
[self updateBars];
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:#selector(stopwatch) userInfo:nil repeats:NO];
}
}
- (void)updateBars
{
if ((NSInteger)hourFrame.size.height != hourInt) { // check if we need to modify
hourFrame.origin.y -= ((hourInt * 10.0) - hourFrame.size.height);
hourFrame.size.height = (hourInt * 10.0);
self->hourBar.frame = hourFrame;
}
if ((NSInteger)minuteFrame.size.height != minuteInt) { // check if we need to modify
minuteFrame.origin.y -= ((minuteInt * 4.0) - minuteFrame.size.height);
minuteFrame.size.height = (minuteInt * 4.0);
self->minuteBar.frame = minuteFrame;
}
if ((NSInteger)secondFrame.size.height != (secondInt * 4.0)) { // check if we need to modify
secondFrame.origin.y -= ((secondInt * 4.0) - secondFrame.size.height);
secondFrame.size.height = (secondInt * 4.0);
self->secondBar.frame = secondFrame;
}
}
- (void)swapFrames
{
hourFrame = self->hourBar.frame;
minuteFrame = self->minuteBar.frame;
secondFrame = self->secondBar.frame;
}
I separated the code so that just before the view appear it should update the bars. However, it did not work. I did some investigating by printing out the values of some of the variables at certain points. It appears that in viewWillAppear, secondBar.frame (and minuteBar, etc.) has updated to the correct height. However, in viewDidAppear, that value is reset to 0. This does not happen to secondInt, or secondFrame. Somewhere between those two methods the frame is reset but I cannot figure it out.
From what I understand, the frames for your properties self.hourBar, self.minuteBar and self.secondBar are set to 0 when you switch between tabs, and only update them every second.
If this is indeed the case, just set them to their correct values in your viewControllers viewWillAppear: method (assign them to some property in viewWillDisappear:).
As a sidenote, you seem to be coming from C++. The "->" notation is very uncommon for Objective-C, since properties are accessed with ".", and their corresponding instance variable with "->". Using the arrow notation will not call the auto-synthesised getter/setter methods of properties!
Also, is there a specific reason why you always create new NSTimer objects instead of setting repeats: to yes? Creating a timer and adding it to a runloop (which scheduledTimerWith:... does) is a relatively costly operation.

Resources