UI按钮崩溃应用程序除了(lldb)之外没有错误

Jon*_*rft 1 cocoa objective-c ios

我正在处理视图A(createExerciseViewController),它在单击UIButton后添加了视图B(createRoutinePopupViewController).

这部分工作正常,视图添加正常.

然后在视图B(createRoutinePopupViewController)里面我有另一个UIButton.当我点击这个UIButton然后应用程序崩溃,我得到的所有错误是(lldb)并且NSLog没有执行.

但有时候,有时只有在几次崩溃后才能完全执行......

我对iOS开发世界很新,我不知道我做错了什么.

所有UIButton方法都是 strong

有谁知道为什么会发生这种情况?

我认为问题可能在于我如何插入子视图和处理整个子视图?

一个---- createExerciseViewController.m

#import "createExerciseViewController.h"
#import "createExercisePopupViewController.h"
#import "createRoutinePopupViewController.h"

// ....more code

- (IBAction)createRoutine:(id)sender {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];
    [self.view addSubview:[[storyboard instantiateViewControllerWithIdentifier:@"createRoutinePopupView"] view]];
}
Run Code Online (Sandbox Code Playgroud)

这是UIViewController B ---- createRoutinePopupViewController.m

#import "createRoutinePopupViewController.h"
#import "createExerciseViewController.h"
#import "User.h"
#import "Routine.h"

- (IBAction)createRoutine:(UIButton *)sender {
    NSLog(@"Please dont crash");
  }
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

dav*_*281 7

您不应该仅仅为了将视图添加到另一个视图控制器的视图而创建视图控制器.您需要告诉系统您正在将视图从一个控制器移动到另一个控制器,以便它可以进行内务处理.如果你不这样做,一个视图控制器最终拥有一个由另一个视图控制器呈现的视图,因此事件和触摸等会混淆.这可能是导致崩溃的原因.

iOS现在提供了一个"容器视图控制器"机制来管理这种情况,从而告诉系统您正在将视图从一个控制器移动到另一个控制器.

来自Apple的文档:

实现容器的目的是能够将另一个视图控制器的视图(和关联的视图层次结构)添加为容器视图层次结构中的子树.除了容器决定将其放置在屏幕上的位置之外,孩子仍然负责其自己的视图层次结构.添加子视图时,需要确保将事件继续分发给两个视图控制器.您可以通过显式将新视图控制器关联为容器的子项来完成此操作.

在实践中,它比听起来更简单.在createExerciseViewController.m中尝试这样的事情:

    - (IBAction)createRoutine:(id)sender {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];

        CreateRoutinePopupViewController* popupController = [storyboard instantiateViewControllerWithIdentifier:@"createRoutinePopupView"];

        //Tell the operating system the CreateRoutine view controller
        //is becoming a child:
        [self addChildViewController:popupController];

        //add the target frame to self's view:
        [self.view addSubview:popupController.view];

        //Tell the operating system the view controller has moved:
        [popupController didMoveToParentViewController:self];
    }
Run Code Online (Sandbox Code Playgroud)