danny huang
danny huang

Reputation: 155

saving state of UIButton when exiting App and reloading it

I have a custom UIButton on a view, when i press it, it changes state and img. The state of the UIButton stays when i exit the view and come back to it. But when i exit my app and start it again. The state of my custom UIButton is back to default. Is there a way I can save the state of that button when i exit the app?

here below is an example picture

before http://i.minus.com/ibzHa1XCTDwSAJ.png

![after] http://min.us/mtkB3JQRI

and here is my code attempting to do that on -(void)viewDidLoad

UOEventPost *post = (UOEventPost *)self.event;
if(post.postWanted == YES){
    [wantThis setBackgroundImage:[UIImage imageNamed:@"[email protected]"] forState:UIControlStateSelected];
    [wantThis setSelected:TRUE];
    wantThis.titleLabel.text = [NSString stringWithFormat:@"Wanted"];
}else {
    [wantThis setSelected:FALSE];
}

EDIT

  savedState = [[NSUserDefaults standardUserDefaults]boolForKey:@"TheSavedState"];

UOEventPost *post = (UOEventPost *)self.event;
if(post.postWanted == YES){
    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"TheSavedState"];
}else {
    [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"TheSavedState"];
}

if(!savedState){
    [wantThis setSelected:FALSE];
}else {
    [wantThis setBackgroundImage:[UIImage imageNamed:@"[email protected]"] forState:UIControlStateSelected];
    [wantThis setSelected:TRUE];
    wantThis.titleLabel.text = [NSString stringWithFormat:@"Wanted"];
}

Upvotes: 1

Views: 368

Answers (3)

C0D3
C0D3

Reputation: 6549

Just write the state to a file. Read from it, onLoad. Problem solved. Look into reading-writing a file in ios if you need help on that. Or you can use settings as well. That will keep the state even if the user quits the application completely.

Upvotes: 0

bdesham
bdesham

Reputation: 16089

It looks to me like you can just store the selected state as a BOOL and then read it back later. Look into NSUserDefaults to persist information like this across sessions. (The best way to do this for your particular app might be to store an NSArray containing identifiers for each of the events the user wants to participate in.)

Upvotes: 0

user1320885
user1320885

Reputation: 135

Use nsuserdefaults, so it will save as long as the user has your app. And you can overwrite it when needed.

Upvotes: 1

Related Questions