Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

yuraider

macrumors newbie
Original poster
Sep 22, 2011
3
0
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:
Code:
- (void)awakeFromNib
{
    string = @"Hello World";
    
    timer = [NSTimer scheduledTimerWithTimeInterval:5.0
                                    target:self
                                    selector:@selector(doSomething)
                                    userInfo:nil
                                    repeats:YES];
}

-(void)doSomething
{
    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:
Code:
#import <Cocoa/Cocoa.h>

@interface MyClass : NSObject <NSApplicationDelegate>
{
   @private
    NSString* string;
    NSTimer* timer;
}

-(void)doSomething;

@end

What's wrong with my code?
 
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.
 
Last edited:
@gnasher729
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.
 
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).
 
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.
 
@gnasher729
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.

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.
 
Last edited:
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!
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.