如何在Parse中存储自定义对象数组?

时间:2014-07-26 21:06:42

标签: ios objective-c json parse-platform

对于使用Parse的iOS应用程序,我需要将一组自定义对象存储到PFObject中。我尝试这样做,我收到错误:'NSInvalidArgumentException',原因:'JSON写入中的无效类型(JSQMessage)'

有没有办法在Parse中存储自定义对象数组?我似乎无法找到一个好的答案。

供您参考,我在https://github.com/jessesquires/JSQMessagesViewController

使用JSQMessages视图控制器库

我尝试添加到PFObject的数组使用代码初始化:

[[NSMutableArray alloc] initWithObjects:
                        [[JSQMessage alloc] initWithText:initialtext sender:[[PFUser currentUser] objectId] date:[NSDate date]],
                                     nil];

1 个答案:

答案 0 :(得分:1)

如果您的自定义对象符合NSCoding协议,那么是,您可以最明确地保存它们。

以下是Magic:The Gathering set

的示例
@interface MTGSet : NSObject <NSCoding>

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *code;
@property (nonatomic, strong) NSDate *releaseDate;

@end

实施

#import "MTGSet.h"

@implementation MTGSet

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeObject:_code forKey:@"code"];
    [aCoder encodeObject:_releaseDate forKey:@"releaseDate"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    return [self initWithJSONDictionary:
            @{@"name" : [aDecoder decodeObjectForKey:@"name"],
              @"code" : [aDecoder decodeObjectForKey:@"code"],
              @"releaseDate" : [aDecoder decodeObjectForKey:@"releaseDate"]}];
}

@end

用法

MTGSet *set = [MTGSet new];
set.name = @"Magic 2015";
set.code = @"M15";
set.releaseDate = [NSDate date];

NSData *dataFromSet = [NSKeyedArchiver archivedDataWithRootObject:set];
PFObject *object = [PFObject objectWithClassName:@"MyObject"];
object[@"set"] = dataFromSet;
[object save];

MTGSet *unarchivedSet = [NSKeyedUnarchiver unarchiveObjectWithData:object[@"set"]];
NSLog(@"Here's the set: %@", unarchivedSet);

有些库可以使用我推荐的objective-c运行时更容易。

https://github.com/eladb/Parse-NSCoding