Search code examples
iosoopexc-bad-accessobjective-c++nszombie

Zombie NSString when called from another object


I can pass basic data between classes, but when I try to pass a NSString* from my UIApplicationDelegate I get an EXC_BAD_ACCESS / NSZombie.

Is there something special I have to do to return an NSObject? Does this have to do with threading? (I thought the atomic setting on the property would take care of that?)

AppDelegate.h:

@interface AppDelegate : NSObject <UIApplicationDelegate> {
  NSString * currentNoteName;
}
@property (atomic, assign) NSString *currentNoteName;
@end

AppDelegate.m:

- (void)timerCallback:(NSTimer *)timer {
    currentNoteName = [NSString stringWithCString:(tone->freq).c_str() encoding:NSUTF8StringEncoding];

// This works:
    NSLog(@"Current Note Name in timerCallback: %@", currentNoteName);

OtherObject.m:

// Returns a Zombie object & EXC_BAD_ACCESS:
NSString *currentNoteName = [appDelegate currentNoteName];

Solution

  • If not using ARC, you must using retain property:

    @property (atomic, retain) NSString *currentNoteName;
    

    and assign a value for it, using setter:

    self.currentNoteName = [NSString stringWithCString: ...];
    

    and don't forget to release instance of this ivar in your dealloc implementation of AppDelegate:

    - (void) dealloc {
      [currentNoteName release], currentNoteName = nil;
      [super dealloc];
    }