ssj
ssj

Reputation: 881

Unable to access data in one class from another class

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 app 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?

Upvotes: 1

Views: 533

Answers (2)

John Franklin
John Franklin

Reputation: 4912

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];
}

Upvotes: 0

walkytalky
walkytalky

Reputation: 9543

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.

Upvotes: 3

Related Questions