EXC_BAD_ACESS while accessing string
I have defined @propert开发者_JS百科y(nonatomic,retain)NSString *usrId;
then assigned a value like this:
usrId=[Screen.Info valueForKey:@"id"];
Then in dealloc
I am releasing the string usrId
. This code is in a viewController
which I am pushing to navController
, then I'm popping it. But the next time I again push this viewController
, an EXC_BAD_ACESS
happens at the statement above.
Never release an object if you didn't allocated or retained it. When you write:
NSString *usrId = [Screen.Info valueForKey:@"id"];
You are just giving a reference to it, neither allocating nor retaining it. So you can either, use one of the following, then release in the dealloc, or you shouldn't release it at all.
NSString *usrId = [[NSString alloc] initWithString:[Screen.Info valueForKey:@"id"]];
NSString *usrId =[[Screen.Info valueForKey:@"id"] retain];
Try assigning your value as
self.usrId = [Screen.Info valueForKey:@"id"];
or
usrId = [[Screen.Info valueForKey:@"id"] retain];
By doing it as you do it you just assign the value of usrId
to [Screen.Info valueForKey:@"id"]
so when you release it in the dealloc you release whatever is stored in [Screen.Info valueForKey:@"id"]
also. Let me know if this works for you.
Using usrId
directly uses the iVar and not the property so it is not being retained properly. You need to use the dot syntax, so change it to self.usrId = [Screen.Info valueForKey:@"id"];
to use the property.
精彩评论