1

In a project I have to make, I am working with external accessories, and the framework ExternalAccessory.

(I can connect to one and only one accessory).

The connection is easy, sending data is not really difficult.

One thing I would like to do is to store in memory the last connected device, to try to reconnect to it automatically when the application relaunch. (after leaving, so after the first launch.)

So, my problem is that EAAccessory is a custom class object, and could not be stored into NSUserDefaults.

I saw this question to store custom objects :

How to store custom objects in NSUserDefaults

So I would create a NSData with it, but did not succeeded, because EAAccessory does not implements the encodeWithCoder and initWithCoder methods...

Any idea ? For this way or another way to process ?

Community
  • 1
  • 1
Flo Schild
  • 5,104
  • 4
  • 40
  • 55

2 Answers2

0

You should store logically/in a meaningful way that makes sense all the important and persisten properties of the EAAcessory instance in an NSDictionary and store this dictionary in NSUserDefaults. Then you will have to read back this dictionary and perform the inverse convertion (alloc-initting the EAAccessory instance, setting its properties, etc.)

  • Sure, but I think I can make something easier :) – Flo Schild Jul 06 '12 at 09:17
  • Not really. That's how this logic works. How do you think various classes' encodeWithCoder: etc. implementation has been coded? ;) –  Jul 06 '12 at 09:48
  • Yeah, this is why I like these classes or methods that simplify my life :) I am a developer, so I do not want to code too much... ;) – Flo Schild Jul 06 '12 at 12:28
0

I think you can implement the missing methods into a custom EAAccessory category. Maybe somthing like this :

*** interface
@interface EAAccessory (CodecAdditions)
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;
@end

*** implementation 
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeInt:[self name] forKey:@"name"];
    [aCoder encodeInt:[self manufacturer] forKey:@"manufacturer"];
    ...
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self.name = [aDecoder decodeIntForKey:@"name"];
    self.manufacturer = [aDecoder decodeIntForKey:@"manufacturer";
    ...

    return self;
}
FredericK
  • 1,612
  • 1
  • 18
  • 26
  • Okay, I tried something like this, but in the init function, I would begin with a : self = [super init] if (self) { ... } And got and error because EAAccessory does not have a parent class. I'll try it again ! – Flo Schild Jul 06 '12 at 09:15
  • Hummmm after another try, this solution does not work, because of EAAccessory properties are readonly. So I cannot make a self.name = ... – Flo Schild Jul 06 '12 at 09:20