为什么要终止此代码?

时间:2012-08-24 20:39:42

标签: objective-c

我编写了以下代码然后运行。 在之后,当我触摸uibutton时,此应用程序将被终止。

我想知道为何终止。

我怀疑是否自动释放?

是否有人可以明确解释

发布myClass实例的原因

发布myClass并

myClass可以使用自动释放的方式吗?

    @interface MyClass : NSObject
    - (void)testMethod;
    @end

    @implementation MyClass{
        NSMutableArray *array;
    }

    - (id)init{
        if ((self = [super init])) {
            array = [[NSMutableArray alloc] initWithCapacity:0];
        }
        return self;
    }

    - (void)dealloc {
        [array release];
        [super dealloc];
    }

    - (void)testMethod {
        NSLog(@"after init : %@", array);
    }

    @end

    @implementation ViewController {
        MyClass *myClass;
    }

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.

        myClass = [[[MyClass alloc] init] autorelease];  <== cause of ternimate?

        UIButton *aButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        [aButton addTarget:self action:@selector(testArray:) forControlEvents:UIControlEventTouchUpInside];
        aButton.frame=CGRectMake(110.0f, 129.0f, 100.0f, 57.0f);
        [aButton setTitle:@"title" forState:UIControlStateNormal & UIControlStateHighlighted & UIControlStateSelected];
        [self.view addSubview:aButton];

    }

    - (void)testArray:(id)sender {
        [myClass testMethod];
    }
@end

3 个答案:

答案 0 :(得分:1)

myClass = [[[MyClass alloc] init] autorelease];

可能是因为您正在自动释放myClass。它是一个实例变量,因此应该保留(然后在类的dealloc方法中释放)。

答案 1 :(得分:0)

似乎是由于

myClass = [[[MyClass alloc] init] autorelease];

当您触摸按钮时,MyClass的实例已被释放。不要偷懒 - 自动释放终极'解决我的内存管理问题,让我不必考虑'解决方案 - 在这里你只需要使用

myClass = [[MyClass alloc] init];

然后在需要时手动释放它 - 可能在你的ViewController类'-dealloc方法中。

答案 2 :(得分:0)

导致问题的是自动释放。

你应该让myClass成为一个属性。

@implementation ViewController {

    }
    @property (nonatomic, retain) MyClass *myClass;

    @synthesize myClass
    -(void)dealloc
    {
      [myClass release];
      [super dealloc];
    }
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.

        self.myClass = [[[MyClass alloc] init] autorelease];

        UIButton *aButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
        [aButton addTarget:self action:@selector(testArray:) forControlEvents:UIControlEventTouchUpInside];
        aButton.frame=CGRectMake(110.0f, 129.0f, 100.0f, 57.0f);
        [aButton setTitle:@"title" forState:UIControlStateNormal & UIControlStateHighlighted & UIControlStateSelected];
        [self.view addSubview:aButton];

    }

    - (void)testArray:(id)sender {
        [myClass testMethod];
    }