1

这是给我相机模态视图的课程

@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

在应用程序委托运行时,我调用 doSomething:

ViewController *actions = [[ViewController alloc] init];
[actions doSomething];
[actions release];

按下相机按钮后,相机视图加载在应用程序委托中,我调用了dsomething,但没有任何反应,并且返回“相机视图未加载”的 BOOL 为空。

如果我在课堂上调用 doSomething ViewController,它可以正常工作,但在另一个课堂上,它不起作用。

如何访问ViewController类中的变量?

4

2 回答 2

3

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

听起来您已经有一个ViewController设置和工作实例,所以您可能应该使用它而不是创建一个新实例:

ViewController* actions = [self getMyExistingViewControllerFromSomewhere];
[actions doSomething];

如果不是这种情况,您需要将新创建的视图添加到适当的超级视图中,并在尝试使用它之前让它全部正确初始化。

于 2010-08-24T08:06:06.510 回答
0

添加到.h:

@property (readwrite, assign, setter=setCameraLoaded) BOOL isCameraLoaded;

添加到.m:

@synthesize isCameraLoaded;

然后你可以这样做:

if ([actions isCameraLoaded]) {
    [actions setCameraLoaded:FALSE];
}
于 2010-08-24T08:07:31.403 回答