2014-01-22 29 views
-1

我知道這已被張貼了很多次,但我無法得到它的工作,我的代碼沒有錯誤(由Xcode發現),但我想要做的是沒有沒有工作。從另一個類使用變量值Objective-c

1-設置:我有2類,ViewController (UIViewController)GraphView (UIView)

2-什麼我試圖做:我有一個BOOL類型中的ViewController可變plotPressedVC接受一個初始值NO。 一旦按下按鈕(此IBAction位於ViewController.m文件中)plotPressedVC = YES。從這裏,在我的GraphView.m文件中,我有一個if語句,如果pressed = YES符合條件。

3-我的代碼:

ViewController.h

#import <UIKit/UIKit.h> 

@interface ViewController : UIViewController { 
    @public BOOL plotPressedVC; 
} 

- (IBAction)plot:(id)sender; 

@end 

ViewController.h

#import "ViewController.h" 
#import "GraphView.h" 

@implementation ViewController 

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

    plotPressedVC = YES; 
} 

- (IBAction)plot:(id)sender { 
    plotPressedVC = YES; 

    GraphView *plotPress = [[GraphView alloc] init]; 
    plotPress.plotPressed = plotPressedVC; 
} 

@end 

GraphView.h

#import <UIKit/UIKit.h> 


@interface GraphView : UIView { 
    BOOL plotPressed; 
} 

@property (nonatomic) BOOL plotPressed; 

@end 

GraphView.m

#import "GraphView.h" 
#import "ViewController.h" 

@implementation GraphView 

- (void)drawLineGraphWithContext:(CGContextRef)ctx { 

    if (plotPressed == YES) { 
     NSLog(@"yep");  
    } 

    // Other code that I want to be in if statement 
} 

@end 

4-問:我做錯了,如果不按下按鈕plot時已經滿足語句的條件?

編輯:在plot行動的末尾添加NSlog,我得到的值80,-64,-128 ...

- (IBAction)plot:(id)sender { 

    plotPressedVC = YES; 

    NSLog(@"%hhd",plotPressedVC); 

    GraphView *plotPress = [[GraphView alloc] init]; 
    plotPress.plotPressed = plotPressedVC; 

    NSLog(@"%hhd",plotPress); 

} 

新問題:如何來plotPress比接受其他號碼0還是1?

+0

我編輯的代碼,我添加了一個NSLog,它不給我BOOL值。我想這就是爲什麼,我會編輯問題 – uti0mnia

+0

您的NSLog正在記錄圖形視圖的值。它應該說NSLog(@「%d」,plotPress.plotPressed),但這不是你的代碼的問題。 – jrturton

+0

[Objective-c從另一個類獲取變量](http:// stackoverflow。com/questions/12539183/objective-c-getting-variable-from-another-class) –

回答

2

它被問了很多次,它通常有相同的答案。

的問題是在這裏:

GraphView *plotPress = [[GraphView alloc] init]; 
plotPress.plotPressed = plotPressedVC; 

在這裏,您創建一個新的圖形視圖,在其上設置的值,然後別的什麼也不做它。您需要在現有的圖形視圖中有一個出口或財產,並設置plotPressed值。

目前,圖形視圖永遠不會被添加到另一個視圖,並且在ARC下將立即在方法結束時釋放。

+0

如何創建一個屬性到現有的GraphView?我以爲'plotPressed'是財產? – uti0mnia

+0

如果您在界面構建器中創建了佈局,則需要製作插座並將其連接起來。那裏有數百個教程。 – jrturton

+0

@KChockey - 認爲是必需的。 –