views:

60

answers:

2

I get an 'EXC_BAD_ACCESS' error when trying to access variable in a function other than the one it was set in

The variable is set in the 'awakeFromNib' function:

//Retrieve Session-ID
sessionID = [self getSessionID];

And accessed in 'searchBtnClick':

NSLog(@"Commening search (%@)",sessionID); // This causes the error

The variable itself is defined in the header:

NSString *sessionID;

Can someone suggest what might be wrong with that?

The part which of getSessionID which returns the value:

NSString *pC = @"";

// Separate Session ID
pC = [initCookie substringFromIndex:10];
pC = [pC substringToIndex:32];

NSLog(@"Got session ID :  %@",pC);

return pC;
+6  A: 

If getSessionID follows normal Cocoa conventions, it returns an autoreleased object. You need to retain it, or sessionID will become a dangling pointer as soon as the autorelease pool is drained (probably at the end of the event loop).

If you are new to Objective C and Cocoa, you should make sure to read the Apple documentation about the memory model.

smorgan
... and how to do that ?
Nick Brooks
Fair enough ... [sessionID retain];
Nick Brooks
This is another good site for some quick ObjC intros/help etc.http://cocoadevcentral.com/
Justin
+4  A: 

Your -getSessionID method is returning an autoreleased variable—when you try to access the pointer again later, the string's already been deallocated and so the reference is no longer valid. You need to call -retain on the variable when you first retrieve it, like this:

 sessionID = [[self getSessionID] retain];

Then, later, in your class's -dealloc, you need to balance the retain with a release:

 [sessionID release];
Noah Witherspoon