【问题标题】:Unable to access data in one class from another class无法从另一个类访问一个类中的数据
【发布时间】:2011-04-03 00:55:23
【问题描述】:

这是给我一个相机模式视图的类

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

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

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

如何访问ViewController 类中的变量?

【问题讨论】:

    标签: iphone objective-c cocoa-touch instance-variables


    【解决方案1】:

    添加到.h:

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

    添加到 .m:

    @synthesize isCameraLoaded;
    

    你可以这样做:

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

    【讨论】:

      【解决方案2】:

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

      听起来您已经设置了一个 ViewController 实例并可以正常工作,因此您可能应该使用它而不是创建一个新实例:

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

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

      【讨论】:

      • 天哪,我没想到这么快就有答案了!是的,ViewController 的实例已设置并正在工作。我理解你的逻辑,但是,我不知道如何“getMyExistingViewControllerFromSomewhere”。
      • 好的,我修复了它,我第一次从笔尖启动 ViewController 作为@interface 中的“UIViewController”,现在我只是将“UIViewController”切换为“ViewController”(类名)。然后我将指针用作“getMyExistingViewControllerFromSomewhere”。你太棒了!
      猜你喜欢
      • 2012-05-03
      • 2017-08-18
      • 2014-01-18
      • 2012-05-18
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      相关资源
      最近更新 更多