开发者

Garbage Collection question in Cocoa

I have the following code in a Cocoa program. In this code, theList is a pointer to an NSMUtableArray object and input is an NSTextField pointer.

-(IBaction)addItem:(id)sender
{
   NSString *item = [input stringValue];
   [theList addObject:item];
    . . .
}

When the program runs and this method is called, I get an access violation on the line [theList addObject:item]. As a last resort, I turned garbage collection on and the code works without any problem. I don't understand why it doesn't work wi开发者_如何学Pythonthout the garbage collector. Can someone explain? Thanks


You probably didn't initialize your array correctly. It's common to see people initializing ivars with autoreleased objects:

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

This won't work. When your method is called no-one guarantees that the array still exist. Turning the garbage collector on will leave the memory management task with it, which understands that you want to use the array later and manages it correctly.

Under traditional memory management rules, use something like this:

array = [[NSMutableArray alloc] init];

Please post your code, where the array is initialized.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜