gpt4 book ai didi

ios - 子类 NSManagedObject 以轻松初始化

转载 作者:行者123 更新时间:2023-11-28 21:15:23 26 4
gpt4 key购买 nike

对于来自服务器 API 的模型,我使用这样的构造函数:

@implementation MenuAPIModel

-(instancetype)initWithServerData:(id)data{

self = [super initWithServerData:data];
return self;
}

-(void)performMapping{

_basketId = self.serverData[@"basket_id"];
_orderId = self.serverData[@"order_id"];
_itemId = self.serverData[@"id"];
_name = self.serverData[@"name"] == [NSNull null] ? @"" : self.serverData[@"persons"];
_payedFrom = [self.dfDetail dateFromString:self.serverData[@"payed_from"]] == nil ? [self.dfBasic dateFromString:self.serverData[@"payed_from"]] : [self.dfDetail dateFromString:self.serverData[@"payed_from"]];
_payedTill = [self.dfBasic dateFromString:self.serverData[@"payed_till"]] == nil ? [self.dfBasic dateFromString:self.serverData[@"payed_till"]] : [self.dfDetail dateFromString:self.serverData[@"payed_till"]];
_persons = self.serverData[@"persons"] == [NSNull null] ? @"2-3" : self.serverData[@"persons"];
_price = self.serverData[@"price"] == [NSNull null] ? @(0) : self.serverData[@"price"];
_price3 = self.serverData[@"price3"] == [NSNull null] ? @(0) : self.serverData[@"price3"];
_price12 = self.serverData[@"price12"] == [NSNull null] ? @(0) : self.serverData[@"price12"];
_status = self.serverData[@"status"] == [NSNull null] ? @"not_payed" : self.serverData[@"persons"];
}

因此,我可以通过简单地编写来创建对象:[MenuAPIModel initWithServerData:data];

现在我将 NSManagedObject 子类化并想知道,我如何将 XCode 为我创建的这 4 个文件子类化,以使构造函数像上面的那样?

最佳答案

您可以创建一种可以具有以下实现的助手(这只是示例,所以我使用了 Swift):

static open func createObject <T : NSManagedObject> (_ objectType : T.Type, record : Dictionary<String, Any>? = nil, context : NSManagedObjectContext) -> (T)
{
let newObject = NSEntityDescription.insertNewObject(forEntityName: String(describing: objectType), into: context)

// Error never occured

var typedNewObject = newObject as! T

guard let trueRecord = record
else
{
return typedNewObject
}

typedNewObject = updateObject(typedNewObject, record: trueRecord, context: context)

return typedNewObject
}

static open func updateObject <T : NSManagedObject> (_ object : T, record : Dictionary<String, Any>, context : NSManagedObjectContext) -> (T)
{
for (key, value) in record
{
setValue(value, key: key, object: object)
}

return object
}

static public func setValue (_ value : Any, key : String, object : NSManagedObject) -> (Void)
{
object.setValue(value, forKey: key)
}

使用这些方法,您可以输入:

let myNewObject = Helper.createObject(YourClassName.self, record: yourDictionary, context: yourContext) // Helper, or any other class name you give it.

我希望它足够接近您的需要。

关于ios - 子类 NSManagedObject 以轻松初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41466655/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com