Iphone 无法从另一个类访问一个类中的数据

Iphone 无法从另一个类访问一个类中的数据,iphone,objective-c,cocoa-touch,instance-variables,Iphone,Objective C,Cocoa Touch,Instance Variables,这是一节课,它给了我一个相机的模态视图 @interface ViewController : UIViewController <UIImagePickerControllerDelegate> { UIImagePickerController *cameraView; // camera modal view BOOL isCameraLoaded; } @property (nonatomic, retain) UIImagePickerController *ca

这是一节课,它给了我一个相机的模态视图

@interface ViewController : UIViewController <UIImagePickerControllerDelegate> {
  UIImagePickerController *cameraView; // camera modal view
  BOOL isCameraLoaded;
}

@property (nonatomic, retain) UIImagePickerController *cameraView; 
- (IBAction)cameraViewbuttonPressed;
- (void)doSomething;
@end

@implementation ViewController

@synthesize cameraView;
- (void)viewDidLoad {
  cameraView = [[UIImagePickerController alloc] init];
  cameraView.sourceType =   UIImagePickerControllerSourceTypeCamera;
  cameraView.cameraOverlayView = cameraOverlayView;
  cameraView.delegate = self;
  cameraView.allowsEditing = NO;
  cameraView.showsCameraControls = NO;
}

- (IBAction)cameraViewbuttonPressed {       
 [self presentModalViewController:cameraView animated:YES];
 isCameraLoaded = YES;
}

- (void)doSomething {
  [cameraView takePicture];
  if ([cameraView isCameraLoaded]) printf("camera view is laoded");
  else {
    printf("camera view is NOT loaded");
  }
}

- (void)dealloc {
  [cameraView release];
  [super dealloc];
}

@end
在我按下相机按钮后,cameraview加载 在应用程序委托中,我调用dosomething,但什么也没有发生,我得到BOOL的null,它返回“摄影机视图未加载”

如果我在
ViewController
类中调用doSomething,它可以正常工作,但是在另一个类中,它不工作


如何访问
ViewController
类中的变量?

您的问题不是访问变量,而是您正在使用
alloc
/
init
从头开始创建一个新的
ViewController
,然后立即尝试使用它,就好像它完全安装在视图层次结构中一样。请注意,
cameraView
是在
viewDidLoad
中设置的,新的视图控制器永远不会调用它

听起来您已经有了一个
ViewController
的实例进行了设置和工作,因此您可能应该使用该实例,而不是创建一个新实例:

ViewController* actions = [self getMyExistingViewControllerFromSomewhere];
[actions doSomething];
如果不是这样,则需要将新创建的视图添加到相应的superview中,并在尝试使用它之前对其进行适当初始化。

添加到.h:

@property (readwrite, assign, setter=setCameraLoaded) BOOL isCameraLoaded;
在.m中添加:

@synthesize isCameraLoaded;
然后,您可以执行以下操作:

if ([actions isCameraLoaded]) {
    [actions setCameraLoaded:FALSE];
}

天哪,我没想到会这么快得到答复!是的,ViewController实例已设置并正在运行。我理解您的逻辑,但是,我不知道如何“从某处获取MyExistingViewControllerFromsomeone”。好的,我修复了它,我第一次从nib启动ViewController,作为@interface中的“UIViewController”,现在我只是将“UIViewController”切换到“ViewController”(类名)。然后我将指针用作“getMyExistingViewControllerFromSomewhere”。你真棒!
if ([actions isCameraLoaded]) {
    [actions setCameraLoaded:FALSE];
}