gpt4 book ai didi

ios - 核心数据 - 等效于使用类别/示例 - Swift

转载 作者:搜寻专家 更新时间:2023-11-01 05:59:32 24 4
gpt4 key购买 nike

我想知道如何从本质上为我的 CoreData NSManagedObject 客户端创建一个类别的等价物:

我知道 Extensions 现在是 Swift 中 Categories 的替代品——但是我不确定它们的实现。这是我在下面扣除的内容:

class Client: NSManagedObject {

@NSManaged var name: String
@NSManaged var projects: NSSet

}

extension Client {

func addClientWithName(name:NSString, context:NSManagedObjectContext) -> Client {
var client:Client = Client();

// Check for name in the database already exists
let request:NSFetchRequest = NSFetchRequest(entityName: "Client")
let sortDescriptor:NSSortDescriptor = NSSortDescriptor(key: "name", ascending: true)
let sortDescriptorsAry:NSArray = [sortDescriptor]
request.sortDescriptors = sortDescriptorsAry
request.predicate = NSPredicate(format: "name = %@", name)

var error:NSError?
let matches:NSArray = context.executeFetchRequest(request, error: &error)

if matches.count == 0 {

//Add new Client
var newClient:NSEntityDescription = NSEntityDescription.insertNewObjectForEntityForName("Client", inManagedObjectContext: context) as NSEntityDescription
newClient.setValue(name, forKey: "name")

context.save(nil);

} else {
client = matches.lastObject as Client
}

return client
}
}

然而,对于这个实现,这是我到目前为止得到的错误:

CoreData: error: Failed to call designated initializer on NSManagedObject class "Ttc9AppName6Client"

关于可能导致此问题的任何想法?

编辑:这就是我从其他类调用方法的方式:

@IBAction func saveBtnTapped(UIButton) {
println("save btn tapped")
var client:Client = Client().addClientWithName("Woofy Face", context: self.managedObjectContext)
}

最佳答案

我认为您的问题与类别/扩展无关。

 var client:Client = Client();

调用 NSManagedObject 的指定初始值设定项,并且此对象如果提取请求没有找到匹配的对象,则返回。

在这种情况下,您可能想要返回新创建的对象。

还要注意

insertNewObjectForEntityForName:inManagedObjectContext:

返回托管对象,而不是实体描述。

此外,

var client:Client = Client().addClientWithName(...)

还创建了一个 Client 对象而不使用指定的初始化器。您应该将方法定义为类方法

所以你的代码应该是这样的:

 class func addClientWithName(name:NSString, context:NSManagedObjectContext) -> Client {
var client:Client

let request:NSFetchRequest = NSFetchRequest(entityName: "Client")
let sortDescriptor:NSSortDescriptor = NSSortDescriptor(key: "name", ascending: true)
let sortDescriptorsAry:NSArray = [sortDescriptor]
request.sortDescriptors = sortDescriptorsAry
request.predicate = NSPredicate(format: "name = %@", name)

var error:NSError?
let matches:NSArray = context.executeFetchRequest(request, error: &error)

if matches.count == 0 {
//Add new Client
client = NSEntityDescription.insertNewObjectForEntityForName("Client", inManagedObjectContext: context) as Client
client.name = name
context.save(nil)
} else {
client = matches.lastObject as Client
}
return client
}

它会被称为

let client:Client = Client.addClientWithName("Woofy Face", context: self.managedObjectContext)

关于ios - 核心数据 - 等效于使用类别/示例 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25107032/

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