简体   繁体   English

为什么NSArray的对象在ARC模式下不调用dealloc methon?

[英]Why NSArray's object not calling dealloc methon under ARC mode?

I am new in Objective-C, the referenced count make me confused :-( . In ARC mode under Xcode 5.0.2, when I create a NSArray init with the objects, the dealloc methon of the object is not invoked, Why? Should I remove the objects from the Array manually?But it's a NSArray, how? here is my test code: 我是Objective-C的新手,引用的计数让我感到困惑:-(。在Xcode 5.0.2下的ARC模式下,当我创建带有对象的NSArray初始化时,为什么不调用对象的dealloc methon,为什么?我手动从阵列中删除了对象,但这是一个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;
}

[NSArray arrayWithObjects:…] returns an autoreleased object, and your program does not provide an autorelease pool. [NSArray arrayWithObjects:…]返回一个自动释放的对象,并且您的程序不提供自动释放池。 (This used to cause runtime warnings in older releases of iOS/OS X.) (这曾经在较旧的iOS / OS X版本中引起运行时警告。)

If you use 如果您使用

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

or add an autorelease pool: 或添加自动释放池:

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;
}

then you will see your dealloc again. 那么您将再次看到您的dealloc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM