-1

I have this Object:

@interface EasySortDevices : NSObject

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *iconName;
@property (nonatomic) Class deviceObject;

@end

How can I encode and decode the Class property deviceObject?

PS: it doesn't work with:

- (void)encodeWithCoder:(NSCoder *)aCoder {

     [aCoder encodeObject:self.name forKey:@"name"];
     [aCoder encodeObject:self.iconName forKey:@"iconName"];
     [aCoder encodeObject:self.deviceObject forKey:@"deviceObject"];
}
Pranjal Bikash Das
  • 1,092
  • 9
  • 27
Goga Eusebiu
  • 29
  • 1
  • 5
  • "it doesn't work" is not a helpful statement. If what way exactly doesn't it work? Do you get a compiler warning or error? A runtime error or crash? Does it just not behave as expected? [Edit] your question to clearly explain your actual issue and include all relevant details. – rmaddy Nov 01 '17 at 15:16
  • 2
    You can use `NSStringFromClass(...)` and `NSClassFromString(...)` to convert it to a string and back which is (en/de)codable – dan Nov 01 '17 at 15:27

2 Answers2

1

the deviceObject should support NSCoding. So to encode a custom object you have to provide for it encode and decode methods.
P.S The encode method your write is good, it only needs that deviceObject to implement encode and decode as well.

Iosif
  • 353
  • 2
  • 15
0

Restricting Coder Support

Follow this apple link:- https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Archiving/Articles/codingobjects.html

In some cases, a class may implement the NSCoding protocol, but not support one or more coder types. For example, the classes NSDistantObject, NSInvocation, NSPort, and their subclasses adopt NSCoding only for use by NSPortCoder within the distributed objects system; they cannot be encoded into an archive. In these cases, a class can test whether the coder is of a particular type and raise an exception if it isn’t supported. If the restriction is just to limit a class to sequential or keyed archives, you can send the message allowsKeyedCoding to the coder; otherwise, you can test the class identity of the coder.

Or if you using Object Encoding and Decoding with NSSecureCoding Protocol

NSCoding is a fantastically simple and convenient way to store data on iOS or Mac OS by turning your model objects directly into a file and then loading it back into memory again, without needing to write any file parsing and serialization logic. To save any object to a data file (assuming that it implements the NSCoding protocol), you can just do this:

Class * deviceObject = [[Class alloc] init];
[NSKeyedArchiver archiveRootObject:deviceObject toFile:deviceObject];

And to load it again later:

Class *deviceObject = [NSKeyedUnarchiver unarchiveObjectWithFile:deviceObject];
BuLB JoBs
  • 841
  • 4
  • 20