Reputation: 15138
I can't belice I am asking this, but im very crazy with this variable stuff.
I want to save a username information. I load them at the load of my view. After this I will get the information when I click on a button.
Here is my code:
@interface SelfViewController : UIViewController
{
NSString *usernameString;
}
- (void)viewDidLoad
{
usernameString = @"test";
}
- (IBAction)goToProfileButtonPressed:(id)sender
{
NSLog(@"%@", usernameString); //CRASH BAD EXEC
}
What did I wrong????
Upvotes: 0
Views: 107
Reputation: 8526
Change your .h file to:
@interface SelfViewController : UIViewController {
NSString *usernameString;
}
@property (retain, nonatomic) NSString *usernameString;
Then in your .m file:
@synthesize usernameString;
- (void)viewDidLoad {
self.usernameString = @"test";
}
- (IBAction)goToProfileButtonPressed:(id)sender {
NSLog(@"%@", self.usernameString); // "self." can be omitted, but it is best practice not to
}
- (void)dealloc {
[usernameString release];
[super dealloc];
}
The problem is that you assign usernameString
to an autoreleased string object. By the time the button is pressed, usernameString
has been released and has become garbage memory. By retaining it (and subsequently releasing it in -dealloc
to avoid a leak) you know that it will not be prematurely released.
Upvotes: 1
Reputation: 3300
You need to synthesize the ivar and add it as a property. (For not-ARC compiling):
in the .h:
@interface SelfViewController : UIViewController
{
NSString *usernameString;
}
@property (nonatomic, retain) NSString *usernameString;
in the .m:
@synthesize usernameString;
Upvotes: 0