Objects get dealloc-ed automatically

Discussion in 'Mac Programming' started by yuraider, Sep 22, 2011.

  1. yuraider macrumors newbie

    Sep 22, 2011
    Hi there,
    I'm very new to Mac programming and I'm using XCode to build my application.
    I have this code in my implementation file:
    - (void)awakeFromNib
        string = @"Hello World";
        timer = [NSTimer scheduledTimerWithTimeInterval:5.0
        NSAlert *alert = [[[NSAlert alloc] init] autorelease];
        [alert setMessageText:string];   <<< This line crashes with EXC_BAD_ACCESS error
        [alert runModal];
    But when my timer fires, I can't seem to access my string anymore. It's like it got automatically dealloc-ed.

    This is the header file:
    #import <Cocoa/Cocoa.h>
    @interface MyClass : NSObject <NSApplicationDelegate>
        NSString* string;
        NSTimer* timer;
    What's wrong with my code?
  2. gnasher729, Sep 22, 2011
    Last edited: Sep 22, 2011

    gnasher729 macrumors P6


    Nov 25, 2005
    Read the documentation for "scheduledTimerWithTimeInterval". Find the line where it says about the selector:

    "The message to send to target when the timer fires. The selector must have the following signature: "

    and compare it with your selector.
  3. yuraider thread starter macrumors newbie

    Sep 22, 2011
    Please read my posts thoroghly. I put 'autorelease' only on the NSAlert object and not the string, but it's the string that gets released.
  4. admanimal macrumors 68040

    Apr 22, 2005
    String literals are never deallocated, so there must be something more subtle going on here. Just for fun, add a [string retain] line after the assignment in awakeFromNib and see if that makes any difference (I don't see why it should).
  5. basher macrumors 6502


    May 27, 2011
    Glendale, AZ USA
    What happens if you use applicationDidFinishLaunching instead of awakeFromNib?

    I remember reading something about trying to get some things working from awakeFromNib can be problematic.
  6. xStep, Sep 22, 2011
    Last edited: Sep 22, 2011

    xStep macrumors 68000

    Jan 28, 2003
    Less lost in L.A.
    Perhaps, but first fix the method signature. Your doSomething method is improperly declared. gnasher729 was kind enough to point that out to you.

    Oh, I dropped your code into an app delegate of a quicky test project and it worked fine, with and without the fixed method signature. So you do have a puzzle.
  7. yuraider thread starter macrumors newbie

    Sep 22, 2011
    After hours of freaking out over this, I found that the problem was assigning a string to a different string pointer, rather than copying the string using [NSString copy].

    Thanks for the help, guys!

Share This Page