为现有的PFObject子类添加和初始化一个新的属性 [英] Adding and initialising a new property for an existing PFObject subclass

查看:163
本文介绍了为现有的PFObject子类添加和初始化一个新的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个现有的Parse数据库,有几个PFObject子类。



如果我想为一个子类添加一个新的属性,例如数组,我将它添加到PFObject子类中,作为一个@property,并将其声明为@dynamic实现。我将其初始化为空的新对象。

  @dynamic newArray; 

+(instancetype)对象
{
MyObject * myObject = [super object];
myObject.newArray = [NSMutableArray array];
return myObject;
}

但是,如何确保已为现有对象初始化这个对象,因为访问此旧对象的属性导致崩溃。



我想我可以覆盖getter,但是我会丢失所有的Parse样板代码,不知道这是明智的。目前我必须清空我的数据库,以确保所有新对象都具有正确的属性。但这显然在现实世界中无法奏效。

解决方案

这是我开发我的Parse应用程序时遇到的一个问题,但是我没有预先存在的实例的问题没有指定键的值的对象。



这个问题的一个解决方案是设置一个运行在所有预先存在的对象中的云代码作业并为必填字段分配默认值。这将使您能够将客户端的复杂性降至最低,允许轻松更新并可能移植到其他系统。



您还应该设置一个beforeSave函数确保所有字段都有默认值,然后拒绝那些不默认值或默认分配默认值的字段。



我的第三个和最后的建议(你似乎正在做的)是确保+对象方法正确地初始化具有所有默认值的对象,以确保固定对象(如果使用LDS)具有正确的默认值。


I have an existing Parse database, with several PFObject subclasses.

If I want to add a new property to a subclass, an array for example, I add it to the PFObject subclass as an @property and declare it @dynamic in the implementation. I initialise it as empty for new objects.

@dynamic newArray; 

+ (instancetype)object
{
    MyObject *myObject = [super object];
    myObject.newArray = [NSMutableArray array];
    return myObject; 
}

But how can I ensure this is initialised for already existing objects, as accessing this property for old objects causes a crash.

I figured I could override the getter, but I would lose all the Parse boilerplate code, and not sure that's wise. Currently I have to empty my db to ensure all new objects have the right properties. But this obviously won't work in the real world.

解决方案

This is a problem that I faced when developing my Parse application as well, but I did not have the problem of preexisting instances of the object that did not have a value for the specified key.

One solution to this problem would be to set up a cloud code job that runs through all the preexisting objects and assigns default values for the required fields. This would enable you to keep the complexity of the client to a minimum, allowing for easy updates and possibly porting to other systems.

You should also set up a beforeSave function that makes sure that all fields have a default value, and then either rejecting ones that don't or silently assigning them a default value.

My third and final recommendation (which you seem to be doing already) is to make sure the +object method properly initializes the object with all default values, in order to ensure that pinned objects (if you're using LDS) have the correct default value.

这篇关于为现有的PFObject子类添加和初始化一个新的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆