开发者

'EXC_BAD_ACCESS' When trying to access a variable?

开发者 https://www.devze.com 2022-12-31 13:57 出处:网络
I get an \'EXC_BAD_ACCESS\' error when trying to access variable in a function other than the one it was set in

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 开发者_如何学Pythonsearch (%@)",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;


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];


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.


I had similar prob, it crashes when you have not allocated any memory. Releasing it like this:

UIImage *lObj_image = [UIImage imageNamed: @"bluebar.png"];

.
.
.

[lObj_image release];

Check in your viewdidload()

0

精彩评论

暂无评论...
验证码 换一张
取 消