2010-06-24 3 views
0

메모리 게임을 개발하고 있습니다. 버튼을 클릭하면 배경이 전환되기를 원합니다. 카드를 두 번째로 클릭하면 배경이 잠시 동안 전환 된 다음 원래 카드로 돌아갑니다. (정확한 카드가 아니라면). 그러나 버튼의 배경은 내가 메소드 (buttonPressed)에서 돌아올 때까지 변경되지 않습니다. 왜 즉시 바뀌지 않습니까? 제발 도와주세요!버튼의 배경 이미지를 변경하고 즉시 업데이트 하시겠습니까?

#import "Button.h" 
#import <UIKit/UIKit.h> 
#import <AVFoundation/AVAudioPlayer.h> 

@class ZogajAppDelegate; 

@interface PairPlayPlayViewController : UIViewController <AVAudioPlayerDelegate> { 
    ZogajAppDelegate *appDelegate; 
    AVAudioPlayer *av; 
    Boolean isPairActive; 
    Button *firstButton; 
    Button *secondButton; 

} 
@property (nonatomic, retain) AVAudioPlayer *av; 
@property (nonatomic, retain) Button *firstButton; 
@property (nonatomic, retain) Button *secondButton; 
- (void)buttonPressed:(id)sender; 
- (void)secondCard; 

@end 

과하는 .m 파일 : : : 여기

내가 작업하고있는 클래스입니다

#import "PairPlayPlayViewController.h" 
#import "ZogajAppDelegate.h" 
#import "Button.h" 
#import "AVFoundation/AVAudioPlayer.h" 



@implementation PairPlayPlayViewController 
@synthesize av, firstButton, secondButton; 

/* 
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. 
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { 
     // Custom initialization 
    } 
    return self; 
} 
*/ 


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. 
- (void)viewDidLoad { 
    [super viewDidLoad]; 

    NSString *newAudioFile = [[NSBundle mainBundle] pathForResource:@"double_card" ofType:@"mp3"]; 
    NSString *newAudioFile2 = [[NSBundle mainBundle] pathForResource:@"right_sound" ofType:@"mp3"]; 

    av = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:newAudioFile] error:NULL]; 
    [av prepareToPlay]; 
    [av initWithContentsOfURL:[NSURL fileURLWithPath:newAudioFile2] error:NULL]; 
    [av prepareToPlay]; 
    //av = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:newAudioFile] error:NULL]; 
    //[av prepareToPlay]; 
    isPairActive = FALSE; 


    appDelegate = (ZogajAppDelegate *)[[UIApplication sharedApplication] delegate]; 
    int position; 

    for(int i = 0; i < ((appDelegate.numberOfPairs*2)/5); i++){ 

     for (int j = 0; j<5 ;j++){ 


      Button *button = [[Button alloc] init]; 

      //Sätter bild nummer.. 
      position = (arc4random() % [appDelegate.cardsInPlay count]); 
      button.picNumber = [[appDelegate.cardsInPlay objectAtIndex:position]intValue]; 
         NSLog(@"%d", button.picNumber); 
      [appDelegate.cardsInPlay removeObjectAtIndex:position]; 

      button.frame = CGRectMake(3 + (65 * j), 5 + (65 * i), 55, 55); 
      button.imageView.contentMode = UIViewContentModeScaleAspectFit; 
      button.imageView.clipsToBounds = YES; 
      [button setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal]; 
      [button addTarget:self action:@selector(buttonPressed:) 
      forControlEvents:UIControlEventTouchUpInside]; 
      [self.view addSubview:button]; 
     } 
    } 
    for (int j = 0; j<((appDelegate.numberOfPairs*2) % 5) ;j++){ 


     Button *button = [[Button alloc] init]; 

     //Sätter bild nummer.. 
     position = (arc4random() % [appDelegate.cardsInPlay count]); 
     button.picNumber = [[appDelegate.cardsInPlay objectAtIndex:position]intValue]; 
     NSLog(@"%d", button.picNumber); 
     [appDelegate.cardsInPlay removeObjectAtIndex:position]; 

     button.frame = CGRectMake(3 + (65 * j), 5 + (65 * ((appDelegate.numberOfPairs*2)/5) + 1), 55, 55); 
     //button.imageView.contentMode = UIViewContentModeScaleAspectFit; 
     //button.imageView.clipsToBounds = YES; 
     [button setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal]; 
     [button addTarget:self action:@selector(buttonPressed:) 
     forControlEvents:UIControlEventAllTouchEvents]; 

     [self.view addSubview:button]; 
    } 
} 


/* 
// Override to allow orientations other than the default portrait orientation. 
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 
    // Return YES for supported orientations 
    return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 
*/ 

-(void)buttonPressed:(id)sender { 
    Button *button = [[Button alloc] init]; 
    button = sender; 
    NSLog(@"%d och spela upp ljud", button.picNumber); 
    NSString *newAudioFile = [[NSBundle mainBundle] pathForResource:@"double_card" ofType:@"mp3"]; 
    [av initWithContentsOfURL:[NSURL fileURLWithPath:newAudioFile] error:NULL]; 
    [av play]; 
    [button setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png",button.picNumber]] forState:UIControlStateNormal]; 
    [self.view addSubview:button]; 
    [NSThread sleepForTimeInterval:1.0]; 

    if(isPairActive == FALSE){ 
     isPairActive = TRUE; 
     firstButton = button; 
    } 
    else { 
     secondButton = button; 
     [self secondCard]; 
    } 

    return; 
} 

- (void)secondCard { 
    [NSThread sleepForTimeInterval:1.0]; 
    NSString *newAudioFile = [[NSBundle mainBundle] pathForResource:@"double_card" ofType:@"mp3"]; 
    isPairActive = FALSE; 
    if([appDelegate.dictionary objectForKey:[NSString stringWithFormat:@"%d",secondButton.picNumber]] == [NSString stringWithFormat:@"%d",firstButton.picNumber]){ 
     NSString *newAudioFile2 = [[NSBundle mainBundle] pathForResource:@"right_sound" ofType:@"mp3"]; 
     [av initWithContentsOfURL:[NSURL fileURLWithPath:newAudioFile2] error:NULL]; 
     [av play]; 
    } 
    else { 
     [firstButton setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal]; 
     [secondButton setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal]; 
     [av initWithContentsOfURL:[NSURL fileURLWithPath:newAudioFile] error:NULL]; 
     [av play]; 
    } 
    return; 
} 

- (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 { 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 


- (void)dealloc { 
    [super dealloc]; 
    [av release]; 
    [firstButton release]; 
    [secondButton release]; 
} 


@end 
+0

NSThread를 사용하는 대신 NSTimer를 사용해야한다고 생각합니다. –

답변

2

변화 buttonPressed:에서 배경,에 NSTimer를 설정 다시 전화하고 돌아온다. NSTimer 콜백에서 배경을 원하는대로 되돌립니다.

당신이 요청한 순간에 드로잉이 발생하지 않습니다. 그것은 당신에게 끔찍한 성과를 줄 것입니다. 모든 도면이 실행 루프의 그리기 부분에 병합됩니다. 이 IBAction 메서드에서 돌아 오기 전까지는 해당 부분에 도달하지 않습니다.

1

이미 알고 계시 겠지만이 방법으로 돌아 오면 이미지가 변경됩니다. 그게 전부 야.

메서드에서 돌아와서 이미지를 변경해야하므로 수행 할 코드의 나머지 부분을 실행하고 메서드에서 반환되는 선택기를 수행해야합니다.

UIKit은 주 스레드에서만 실행할 수 있으므로 메서드에서 돌아와야하므로 블로킹이되어 GUI 조작이 실행됩니다.

EDIT : NSThread에 절전 모드를 설정하는 대신 지연 기능을 사용하여 선택기를 수행하십시오.

관련 문제