【问题标题】:Why NSArray's object not calling dealloc methon under ARC mode?为什么 NSArray 的对象在 ARC 模式下不调用 dealloc 方法?
【发布时间】:2013-12-13 14:53:21
【问题描述】:

我是 Objective-C 的新手,引用的计数让我感到困惑 :-( 。 在Xcode 5.0.2下的ARC模式下,当我用对象创建一个NSArray init时,没有调用对象的dealloc方法,为什么?我应该手动从数组中删除对象吗?但它是一个 NSArray,如何?这是我的测试代码:

//------LCDRound.h file-------------
@interface LCDRound : NSObject
- (void)paint;
@end
//------LCDRound.m------------------
@implementation LCDRound
- (void)paint
{
    NSLog(@"I am Round");
}
- (void)dealloc
{
    NSLog(@"Round dealloc");
}
@end

//-------main.m---------------------
#import <Foundation/Foundation.h>
#import "LCDRound.h"
int main(int argc, const char * argv[])
{
    LCDRound* round1 = [[LCDRound alloc] init];
    LCDRound* round2 = [[LCDRound alloc] init];
    NSArray* objects = [NSArray arrayWithObjects:round1, round2, nil];
    for (LCDRound* shape in objects) {
        [shape paint];
    }
    return 0;
}

【问题讨论】:

  • 在您的示例中,您希望在哪里调用 dealloc?

标签: ios objective-c nsarray automatic-ref-counting dealloc


【解决方案1】:

[NSArray arrayWithObjects:…] 返回一个自动释放的对象, 并且您的程序不提供自动释放池。 (这曾经导致运行时 旧版本 iOS/OS X 中的警告。)

如果你使用

NSArray* objects = [[NSArray alloc] initWithObjects:round1, round2, nil];

或添加自动释放池:

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        LCDRound* round1 = [[LCDRound alloc] init];
        LCDRound* round2 = [[LCDRound alloc] init];
        NSArray* objects = [NSArray arrayWithObjects:round1, round2, nil];
        for (LCDRound* shape in objects) {
            [shape paint];
        }
    }
    return 0;
}

然后你会再次看到你的dealloc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 2012-03-09
    • 1970-01-01
    • 2013-10-19
    • 2012-11-30
    相关资源
    最近更新 更多