2012-08-11 1 views
-3

저는 스토리 보드를 사용하여 기본 게임을 만들고 있습니다. 나는 여러 개의 뷰 (물론)를 가지고 있으며 뷰를 다시 열 때 리셋한다. 그래서 appdelaget이 객체를 만들어야하는 클래스를 만들었습니다. 이제보기를 다시로드 할 때 변수를 전달해야하거나 재설정하지 않을 모든보기에 appdelaget을 가져옵니다. 자, 사람이 어떻게 다른 개체 안에 만들어진 개체에서 변수를 얻을 줄 알아.개체의 개체에서 변수를 가져 오는 방법 (Objective-C)

VariableControll.h :

#import <Foundation/Foundation.h> 

@interface VariableControl : NSObject 

@property (nonatomic) int maxNr; 
@property (nonatomic) int nrSet; 
@property (nonatomic) int guessNr; 

VariableControll.m :

#import "VariableControl.h" 

@implementation VariableControl 

@synthesize maxNr; 
@synthesize guessNr; 
@synthesize nrSet; 

@end 

이 변수를 저장하는 간단한 클래스입니다 어쨌든, 그것은 설명하기 어려운, 여기에 중요한 클래스는 그것은 전망을 통과 할 것입니다.

Appdelaget.h :

#import <UIKit/UIKit.h> 
#import "VariableControl.h" 

@interface AppDelegate : UIResponder <UIApplicationDelegate> 

@property (strong, nonatomic) UIWindow *window; 

@end 

Appdelaget.m :

#import "AppDelegate.h" 

@implementation AppDelegate 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:     
(NSDictionary *)launchOptions 
{ 
    VariableControl *VarControll = [[VariableControl alloc] init]; 

    VarControll.maxNr = 100; 

    VarControll.nrSet = arc4random() %VarControll.maxNr; 

    // Override point for customization after application launch. 
    return YES; 
} 
//More methods are not listed becouse they're non-touched// 

Game.h :

#import <UIKit/UIKit.h> 
#import "AppDelegate.h" 

@interface Game : UIViewController 

//User interaction and labels 
@property (strong, nonatomic) IBOutlet UILabel *theTitle; 
@property (strong, nonatomic) IBOutlet UITextField *theInput; 
@property (strong, nonatomic) IBOutlet UILabel *theMessage; 
@property (strong, nonatomic) IBOutlet UINavigationItem *theTabTitle; 
@property (strong, nonatomic) IBOutlet UIButton *theGuessButton; 
@property (strong, nonatomic) IBOutlet UIButton *theNewGameButton; 

//Variables 
@property (nonatomic) int number; 
@property (nonatomic) int guess; 
@property (nonatomic) int nrOfGuess; 
@property (nonatomic) int maxNr; 
@property (nonatomic, retain) NSString *guessString; 

//Actions 
- (IBAction)guess:(id)sender; 
- (IBAction)newGame:(id)sender; 

@end 
//Have some non-neded outlets becouse I tried to fix SIGABRT error, and didn't remove 
them(btw, I have solved sigabrt!!!!)// 

Game.m :

#import "Game.h" 

@implementation Game 

@synthesize theTitle; 
@synthesize theInput; 
@synthesize theMessage; 
@synthesize theTabTitle; 
@synthesize theGuessButton; 
@synthesize theNewGameButton; 
@synthesize number; 
@synthesize nrOfGuess; 
@synthesize guess; 
@synthesize guessString; 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: 
(NSDictionary *)launchOptions 
{ 
    AppDelegate *StartUp = [[AppDelegate alloc] init]; 

    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. 

    //When the user taps somwhere away from the keyboard, it disapears 
    [theInput resignFirstResponder]; 

    [theTabTitle setTitle:@"Game"]; 

    [theNewGameButton setTitle:@"New Game" forState:UIControlStateNormal]; 
    [theGuessButton setTitle:@"Guess" forState:UIControlStateNormal]; 

    //set a random number and clear variables 

    nrOfGuess = 0; 
    guess = 0; 
} 

- (void)viewDidUnload 
{ 
    [self setTheTitle:nil]; 
    [self setTheInput:nil]; 
    [self setTheMessage:nil]; 
    [self setTheTabTitle:nil]; 
    [self setTheGuessButton:nil]; 
    [self setTheNewGameButton:nil]; 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
} 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [theInput resignFirstResponder]; 
    //If the user touches outside the keyboard, it will disapear 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation 
{ 
    return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 

- (IBAction)guess:(id)sender { 

    guess = [[theInput text] intValue]; 

    if (guess == number) { 

    guessString = [NSString stringWithFormat:@"Corret! You guessed %i times!", nrOfGuess]; 

    [theMessage setText: guessString]; 

    number = arc4random() %101; 
    nrOfGuess = 0; 
    guess = 0; 

} 

else { 

    if (guess < number) { 

     [theMessage setText:@"Sorry! Guessed too low!"]; 

     nrOfGuess = nrOfGuess + 1; 

     [theInput setText:@""]; 
    } 
    else { 

     [theMessage setText:@"Sorry! Guessed too high!"]; 

     nrOfGuess = nrOfGuess + 1; 

     [theInput setText:@""]; 
     } 
    } 
} 

- (IBAction)newGame:(id)sender { 
    //set a random number and clear variables 
    number = arc4random() %101; 

    nrOfGuess = 0; 
    guess = 0; 
} 
@end 

자, 질문은; game.m에서 "VarControll"에 maxNr 변수를 어떻게 얻을 수 있습니까? appdelaget.m에 VariableControll 클래스의 객체가 만들어졌습니다. 나는 할 수 없다

number = StartUp.VarControll.maxNr; 

그것은 나에게 오류를 줄 것이다!

BTW, 내가 본 바보 같은 질문이나 가장 명백한 대답이 있다면, 나는 목표에 도달하는 초보자입니다. 조언에

고맙습니다, JomanJi

답변

0

나는 귀하의 질문에 잘 즉 이해한다면 이것은, 해결하기 위해 기본적으로 쉽다는 ..

그래서 당신은 다음 뷰에 넘겨해야합니다 몇 가지 변수를 정의?

스토리 보드를 사용 중이므로 segue 명령을 통해이 값을 넘겨 줄 수 있습니다.

빠른 예를 ... viewOne에서

, 당신은 MaxNr라는 변수를 만듭니다. (별도의 클래스를 선언 할 필요가 없습니다!) 당신이 viewTwo에 갈 때

그래서, 다음 SEGUE 라인을 사용

if ([segue.identifier isEqualToString:@"gotoViewTwo"]) 
{ 
UIViewController *viewTwo = [segue destinationViewController]; 
viewTwo.maxNr=self.maxNr; 
} 

이 viewTwo에 MaxNr의 값을 넘겨 것입니다.

보기에서 명백히 선언하고 maxNr을 합성해야합니다.

viewTwo.h 
.... 

@property (nonatomic) (int) maxNr; 

viewTwo.m 
.... 

@synthesize maxNr; 

당신이 당신이 바로, 당신이 행 다음에 viewTwo didLoad에 넣어했다 여부를 확인하려면

:이 도움이

NSLog(@"My viewTwo maxNr value is %u",maxNr); 

희망 ..

+0

이것은 그랬습니다, 고맙습니다! – JomanJi

+0

이 대답을 받아 들일 수 있습니까? –

+0

권자, 나는 내가했다라고 생각했다. ..... 미안하다! – JomanJi

0

는 당신이이다 누락 된 것으로 보인다 무엇 instance variable 또는 property이 무엇인지 이해하고 있으며 이는 Objective-C의 객체 지향 프로그래밍을 이해하는 기본입니다.

속성 "window"이 정의 된 "Appdelaget.h"를 고려하십시오. 이 속성은 AppDelegate의 인스턴스에 속합니다. 그래서 당신은 쓸 수 있습니다 : 그러나 당신의 변수 VarControll는 인스턴스 변수 (즉,이 속한) 클래스하지

AppDelegate *StartUp = [[AppDelegate alloc] init]; // create your instance of AppDelegate 
NSWindow *theWindow = Startup.window; // obtain the value of the window property 

을하지만, 지역 변수하는 방법 (즉 속한) - 그것은 존재에 올 때 메서드가 호출 될 때 파괴됩니다.

Startup.VarControll; // wrong, Startup has no property VarControll 
Startup->VarControll; // also wrong, Startup has no instance variable VarControll 

한 문제에 대한 솔루션이 AppDelegate 클래스 유형 VariableControl의 인스턴스 변수 (또는 속성)를 추가하고 그 설정하여 application:didFinishLaunchingWithOptions: 방법 대신에 지역 변수를 사용하는 것입니다 : 그것은 당신이 쓸 수없는 이유 . 그러나 그것은 당신의 문제에 대한 정답이 아닐 수도 있습니다. 이해를 돕기 위해 지역 변수와 인스턴스 변수, 변수 및 객체의 수명을 읽어 볼 수 있습니다.

+0

그래, 내가 잘못 생각한 것은 내가 지역 변수를 사용하고 인스턴스 변수를 사용하지 않는다고 생각했다. – JomanJi

관련 문제