Question

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:

//------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;
}
Was it helpful?

Solution

[NSArray arrayWithObjects:…] returns an autoreleased object, and your program does not provide an autorelease pool. (This used to cause runtime warnings in older releases of 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top