我可以在 Objective-C 中做到这一点,但我无法弄清楚如何让它在 Swift 中工作。我正在 NSManagedObject 上编写扩展,以便我可以在任何想要创建新实体时简单地调用函数。然后,该函数将检查现有实体是否匹配,如果不匹配,该函数将创建新实体并返回它。如果有匹配,它将返回匹配。这是我的代码:
extension Chapter {
class func createChapter(i_d: Int, team_level: Int, location: String, name: String, school: String, image: UIImage, context: NSManagedObjectContext) -> Chapter {
var chapter : Chapter?
var request : NSFetchRequest = NSFetchRequest(entityName: "Chapter")
request.predicate = NSPredicate(format: "i_d = \(i_d)")
var error : NSError?
var results : [Chapter] = context.executeFetchRequest(request, error: &error) as [Chapter]
if error != nil{
println(error)
} else if results.count == 1 {
println("Only found one Chapter match for id: \(i_d)")
chapter = results.first!
} else if results.count > 1 {
println("Found multiple Chapters for id: \(i_d)")
for chapter in results {
println(chapter.name)
}
} else {
chapter = NSEntityDescription.insertNewObjectForEntityForName("Chapter", inManagedObjectContext: context) as? Chapter
chapter?.i_d = i_d
chapter?.team_level = team_level
chapter?.location = location
chapter?.name = name
chapter?.school = school
chapter?.image = UIImagePNGRepresentation(image)
var error: NSError? = nil
if !context.save(&error) {
println("Saving error \(error), \(error?.userInfo)")
} else {
println("Saved a Chapter with id: \(i_d)")
}
}
return chapter!
}
}
- “i_d”是实体的唯一 ID
这就是我以前在 Objective-C 中调用类似内容的方式(粗略翻译):
Chapter *chapter = [Chapter createChapterWithID:i_d, team_level:team_level, location:location, name:name, school:school, image:image, context:context];
每当我尝试类似 var chap: Chapter = Chapter.createChapter(...) 时,Xcode 只允许我在参数列表中放置另一个 Chapter 对象,而如果我尝试调用该函数从 Chapter 实例中,函数参数可以很好地填写。
我将如何解决我的问题?
编辑:
根据答案建议,我通过将“class”放在函数定义前面,以及在函数中正确创建初始变量并在必要的位置添加问号来修复我的代码。
最佳答案
您可以尝试创建一个方便的 init。
http://devmonologue.com/ios/swift/swift-initializers-designated-convenience/
另请注意,如果您想要执行 Chapter.createChapter(),createChapter 需要是一个类函数,在您的扩展中它只是一个常规函数。所以它期望一个 Chapter 对象来创建对象,而不是类。
改变
func createChapter ...
至
class func createChapter ...
关于NSManagedObject 上的 Swift 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27825284/