Saving UIPrinter to NSUserDefaults

2019-02-21 02:14发布

问题:

I am trying to save a UIPrinter object like this.

-(IBAction)setPrinterInSettings:(id)sender{

  UIPrinterPickerController *picker = [UIPrinterPickerController printerPickerControllerWithInitiallySelectedPrinter:self.SavedPrinter];
  [picker presentFromRect:self.settingsButton.frame inView:self.view animated:YES completionHandler:^(UIPrinterPickerController *controller, BOOL userDidSelect, NSError *err) {
    if (userDidSelect) {
      self.SavedPrinter = controller.selectedPrinter;
      NSLog(@"self.SavedPrinter == %@",self.SavedPrinter);

      [self saveCustomObject:self.SavedPrinter key:@"SavedPrinter"];

          [[NSUserDefaults standardUserDefaults] setObject:self.SavedPrinter forKey:@"SavedPrinter"];
          [[NSUserDefaults standardUserDefaults] synchronize];
    }

  }];

}

It crashes when I try to save at [[NSUserDefaults standardUserDefaults] setObject:self.SavedPrinter forKey:@"SavedPrinter"]; and I get this message as a error -[UIPrinter encodeWithCoder:]: unrecognized selector sent to instance 0x7fb204062760. I need it to remember what printer the user picked and remember it even when the app goes out of the background. If any one could help that would be great!

回答1:

You can't store a UIPrinter instance in NSUserDefaults. What you can do is save the printer's URL and then when your app starts again and you need the UIPrinter, read the URL from NSUserDefaults and use UIPrinter printerWithURL:.



回答2:

You should use the url property to save in NSUserDefaults with setURL:forKey: .

Something like this:

NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];     
[defaults setURL:[self.SavedPrinter url] forKey:@"printer.url"];
[defaults synchronize];

And when you need the same printer again, create another UIPrinter with printerWithURL: using the url you have stored.