【问题标题】:iOS app crashes with EXC_BAD_ACCESSiOS 应用程序因 EXC_BAD_ACCESS 而崩溃
【发布时间】:2013-07-16 21:38:39
【问题描述】:

我包含了完整的项目,所以没有什么是模棱两可的。

啊.h

#import <Foundation/Foundation.h>

@interface A : NSObject
-(void) zero;
@end

上午

#import "A.h"

@implementation A

#define width 3
#define height 3

uint8_t** _board;

-(void) zero
{
for(int i = 0; i < width; i++)
    for(int j = 0; j < height; j++)
        _board[i][j] = 0;
}

-(void)dealloc
{
for(int i = 0; i < width; i++)
    free(_board[i]);
free(_board);
}

-(id) init
{
self = [super init];
if(self)
{
    _board = malloc(sizeof(uint8_t*)*width);
    for(int i = 0; i < width; i++)
        _board[i] = malloc(sizeof(uint8_t)*height);
}
return self;
}

@end

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
@end

ViewController.m

#import "ViewController.h"
#import "A.h"

@implementation ViewController

A* _gameBoard;

- (void)viewDidLoad
{
[super viewDidLoad];

_gameBoard = [[A alloc] init];
[[A alloc] init];

[_gameBoard zero];
}

@end

具体来说,程序在设置_board 时会在函数0 中崩溃。我还想指出,如果您删除

[[A alloc] init];

从 ViewController 的实现来看,程序不会崩溃。提前感谢您的帮助。

【问题讨论】:

  • _gameBoard = [[A alloc] init]; [[A alloc] init]; alloc-init 两次很奇怪

标签: ios objective-c memory-management


【解决方案1】:

board 设为A 类的ivar,您的问题应该会消失。现在它是一个全局的,第二个 [[A alloc] init];freeing 它(看起来你启用了 ARC,llvm 会看到该对象实际上并没有被使用并立即释放它)。

当你调用时

[_gameBoard zero];

它现在正试图引用 free'd 全局 board,这会引发 EXC_BAD_ACCESS 异常。

正如您所发现的,像 board 这样的全局变量通常是个坏主意。

【讨论】:

  • 看起来 Marcelo Fabri 打败了你。你是绝对正确的,我需要创建实例变量。感谢您的帮助。
  • 没关系,只要你把它修好,明白它为什么不起作用。
【解决方案2】:

您的代码中有几个问题。首先,创建另一个A 实例而不将其分配给变量是没有意义的。

但主要问题是您没有在 ViewController (_gameBoard) 和 A (uint8_t** _board) 上使用实例变量(或属性)。

使它们成为实例变量(或属性)应该可以解决您的问题。

PS:您可能还想使用 NSArray 而不是 C 样式的数组。

【讨论】:

  • 谢谢,问题是我不知道把 _board 放在我导致它是静态的地方。我一直认为它是一个实例变量。猜猜我只是不知道语法。无论如何,非常感谢,这个问题对我来说是地狱。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-13
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多