Question

Im using this code when I try to allocate window. However it don't work and the window will just deallocate itself immediately after is is created. Is there any way to prevent this from happening. Also note that I'm using xcode 5 with arc.

    CustomWindow windotest2 = [[CustomWindow alloc] initWithContentRect:frame
                                                                                                                                styleMask:NSBorderlessWindowMask
                                                                                                                                  backing:NSBackingStoreBuffered
                                                                                                                                    defer:NO];

   [windotest2 makeKeyAndOrderFront:NSApp];

    [self.array addObject:windotest2];
Was it helpful?

Solution

To cause the object to stick around, you need to keep a valid pointer to it, but since windotest2 is a local variable, it goes out of scope when your method terminates and if there are no remaining live pointers to the object, the object will be deallocated.

Something you could do to alleviate this, in a generic manner, is:

@implementation myClass {
    NSMutableArray *_retainedObjects;
}

- (id)init
{
    ...
    _retainedObjects = [[NSMutableArray alloc] init];
    ...
}


- (...)yourMethod
{
    CustomWindow windotest2 = [[CustomWindow alloc]...
    ...
    [_retainedObjects addObject:windotest2];
    ...
}

Now your object has a valid pointer after the method returns.

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