ios - NSArray 中的一个对象被释放

标签 ios objective-c automatic-ref-counting

我正在使用 TWTSideMenuViewController 编写应用程序使用 cocoapods 安装。为此,我有一个名为 MenuViewController 的 ViewController,它有一个包含所有单独内容 View Controller 的数组:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _controllerArray = [NSArray arrayWithObjects:
                            [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil],
                            [[AboutMeViewController alloc] initWithNibName:@"AboutMeViewController" bundle:nil],
                            [[ScheduleViewController alloc] initWithNibName:@"ScheduleViewController" bundle:nil],
                            [[FoodViewController alloc] initWithNibName:@"FoodViewController" bundle:nil],
                            [[CalendarViewController alloc] initWithNibName:@"CalendarViewController" bundle:nil],
                            [[AthleticsViewController alloc] initWithNibName:@"AthleticsViewController" bundle:nil],
                            [[DirectoryViewController alloc] initWithNibName:@"DirectoryViewController" bundle:nil], nil];
    }
    return self;
}

然后我使用以下代码设置 TWTSideMenuViewController:

MenuViewController *menuViewController = [[MenuViewController alloc] initWithNibName:@"MenuViewController" bundle:nil];
TWTSideMenuViewController *twtSideMenuViewController = [[TWTSideMenuViewController alloc] initWithMenuViewController:menuViewController mainViewController:[[menuViewController controllerArray] objectAtIndex:0]];
twtSideMenuViewController.zoomScale = .5;
twtSideMenuViewController.edgeOffset = UIOffsetMake(-80, 0);
self.window.rootViewController = twtSideMenuViewController;

所有这一切都完美无缺,但是当我切换到不同的内容 View (除了默认的主页,我尝试返回主页时,我收到 EXC_BAD_ACCESS 错误。我可以在任何其他内容之间来回切换 View Controller ,因为看起来 HomeViewController 是唯一一个被释放的 Controller 。

我觉得这与在设置代码中访问它有关,但是有什么办法可以解决这个问题吗?

最佳答案

您必须将每个 View Controller 的对象声明为强对象并将其传递给数组

@property(strong,nonatomic) HomeViewController *home;



home = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil]
_controllerArray = [NSArray arrayWithObjects:home,aboutme....];

在您的旧代码中,类对象未使用强引用 声明。强引用对象会造成保留循环。这意味着您将成为该对象的所有者。

但是当您将对象声明为本地对象时,您没有对它的强引用。这意味着它将在当前执行循环完成后自动释放。这就是为什么数组中的 HomeViewController 本地对象被释放并显示错误

关于ios - NSArray 中的一个对象被释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20136754/

相关文章:

iphone - 使用 ARC(强/弱)避免循环保留,学习一些基础知识

ios - 对象 : ARC releasing dynamically created view controller too early

ios - 如何使 UITextField 在 IOS 中不可见/隐藏?

ios - NSKeyedArchiver 不保留数据 Swift 3

ios - Objective C 运算符优先级

iphone - 在 iPhone 应用程序中集成 Dropbox 错误 400

objective-c - ARC 中的强大属性 - Objective C

ios - osx 上的 sem_open 共享内存在哪里

ios - 当调用某些函数时变量消失

ios - PrepareForSeque 未调用/触发