How to serialize a class in IOS sdk (Objective-c)?

前端 未结 7 1638
既然无缘
既然无缘 2021-01-03 01:21

How to serialize the following class in objective-c so that it can be used with SBJson?

I get \"JSON serialisation not supported for Animal\" error when I use this c

7条回答
  •  暖寄归人
    2021-01-03 01:36

    Make your custom class conform to NSCoding protocol and then serialize it.

    For more info, visit the Apple documentation

    Also, this link will also help you. As suggested in this link, archive your custom class to NSData and serialize that as provided in the Apple documentation.

    Edit Make your Animal.m as follows:

    #import "Animal.h"
    
    @implementation Animal
    @synthesize name, description, imageURL;
    
    -(id)initWithName:(NSString *)n description:(NSString *)d url:(NSString *)u {
        self = [super init];
        if( self )
        {
           self.name = n;
           self.description = d;
           self.imageURL = u;
        }
        return self;
    }
    
    - (id)initWithCoder:(NSCoder *)aDecoder
    {
        self = [super init];
        if( self )
        {
            self.name = [aDecoder decodeObjectForKey:@"name"];
            self.description = [aDecoder decodeObjectForKey:@"description"];
            self.imageURL = [aDecoder decodeObjectForKey:@"imageURL"];
        }
        return self;
    }
    
    - (void)encodeWithCoder:(NSCoder *)encoder
    {
        [encoder encodeObject:name forKey:@"name"];
        [encoder encodeObject:description forKey:@"description"];
        [encoder encodeObject:imageURL forKey:@"imageURL"];
    }    
    
    @end
    

提交回复
热议问题