开发者

Unable to access data in one class from another class

开发者 https://www.devze.com 2023-01-13 07:41 出处:网络
Here is the class which gives me a modal view of the camera @interface ViewController : UIViewController <UIImagePickerControllerDelegate> {

Here is the class which gives me a modal view of the camera

@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

In the a开发者_开发问答pp delegate when it's running, I call doSomething:

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

After I press the camera button, the cameraview loads In the app delegate I call dosomething but nothing happens and I get null for the BOOL which returns "camera view is NOT loaded".

If I call doSomething in the ViewController class, it works fine, but from another class, it doesn't work.

How can I access the variables in ViewController class?


Your problem isn't accessing the variables, it's that you're creating a new ViewController from scratch with alloc/init and then immediately trying to use it as if it were fully installed in the view hierarchy. Note that cameraView is set up inside viewDidLoad, which won't ever get called for the new view controller.

It sounds like you already have an instance of ViewController set up and working, so probably you should use that rather than creating a new one:

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

If that is not the case, you'll need to add the newly created view to the appropriate superview and let it all initialise properly before trying to use it.


Add to the .h:

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

Add to the .m:

@synthesize isCameraLoaded;

You can then do:

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

精彩评论

暂无评论...
验证码 换一张
取 消