Search code examples
iosobjective-cdecodeencodenscoder

How can you encode and decode Class type object in objective C?


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"];
}

Solution

  • 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];