0

I have an app where I need to track the last button pressed at all times. So I have implemented this method:

-(void) lastButtonPressed: (id)sender
{
    lastButtonPressed = (UIButton *)sender;
}

Then when any button gets pressed I call:

[self lastButtonPressed = xButton];

Works perfect. But now I am working on archiving all of the objects in my app when the view disappears or closes to then unarchive it and UIButton doesn't conform to NSCopying or NSCoding. I have read that I can subclass UIButton and define the methods but I am stuck there.

So when my app closes or the view disappears I want to save the lastButtonPressed.

I created a new class called BIDPersistence to hold my archived data. In my app's view controller I have a saveData method where I save my data. I get an error on the last line shown below because UIButton doesn't conform.

BIDPersistence *persistence = [[BIDPersistence alloc] init];
    persistence.field1 = [NSNumber numberWithDouble:double1];
    persistence.field2 = [NSNumber numberWithDouble:double2];
    persistence.field3 = display.text;
    persistence.field4 = tapeDisplay.text;
    persistence.field5 = [NSNumber numberWithBool:continueTape];
    persistence.field6 = [NSNumber numberWithBool:newDouble];
    persistence.field7 = lastButtonPressed;

Any help appreciated.

d.altman
  • 355
  • 4
  • 15

2 Answers2

1

It sounds like you don't have to save the actual button, just know which one was pressed last. For this you could use NSUserDefaults, which is good for saving little tidbits without having to set up Core Data or the like. What I would recommend is to give each button a unique tag (in interface builder, just an int) then do this:

[[NSUserDefaults standardUserDefaults] setInt:[lastButton tag] forKey:@"LastButtonPressed"];

later you can retrieve the button by using viewWithTag:.

Alex Gosselin
  • 2,942
  • 21
  • 37
  • Or to stay consistent with your code above, store the tag number using BIDPersistance, rather than the button itself. – Alex Gosselin Feb 24 '12 at 23:18
  • Thank you! That did it. I simply get the tag from the last button pressed and save that as an [NSNumber numberWithInt:lastButtonPressed.tag] I have an if statement where I unarchive to assign the button. Works perfectly. Let me know if you see a problem with this approach. – d.altman Feb 25 '12 at 00:44
  • No problem! I don't foresee any problems as long as you use make sure to use unique tag numbers. – Alex Gosselin Feb 25 '12 at 01:57
0

You can't really subclass UIButton. It's not a single class but, as they say, a class cluster that UIKit selects based on UIButton's + (id)buttonWithType:(UIButtonType)buttonType.

That said, it does (appear) to conform to NSCoding (just reading the docs; I don't know how the NSCoding stuff works.)

smparkes
  • 13,807
  • 4
  • 36
  • 61