使用Coredata Swift发送到实例的无法识别的选择器(unrecognized selector sent to instance with Coredata Swift)

编程入门 行业动态 更新时间:2024-10-28 14:30:41
使用Coredata Swift发送到实例的无法识别的选择器(unrecognized selector sent to instance with Coredata Swift)

每当我尝试更新核心数据模型的值时,我都会收到此错误。 这是我的模特

import Foundation import CoreData @objc(Habit) class Habit: NSManagedObject { @NSManaged var name: String @NSManaged var trackingType: NSNumber }

这是我的代码tableViewCell

override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if selected { self.accessoryType = UITableViewCellAccessoryType.Checkmark if self.habit? != nil { self.habit?.trackingType = index } } else { self.accessoryType = UITableViewCellAccessoryType.None } // Configure the view for the selected state }

我一直收到错误“由于未捕获的异常终止应用程序'NSInvalidArgumentException',原因:' - [习惯setTrackingType:]:无法识别的选择器发送到实例0x7fdcbb002c90'”

在线self.habit?.trackingType = index

我在最近2天努力解决这个问题。

编辑:

模型习惯以下面的方式初始化

func getHabits() -> [AnyObject]{ let entityDescription = NSEntityDescription.entityForName("Habit", inManagedObjectContext: managedObjectContext!) let request = NSFetchRequest() request.entity = entityDescription // // let pred = NSPredicate(format: "(trackingType != -1)") // request.predicate = pred var error: NSError? var objects = managedObjectContext?.executeFetchRequest(request, error: &error) return objects!; }

返回的列表在应用程序的任何位置都使用。 基本上我从列表中获取和项目并更新其属性,然后再次保存

I keep getting this error whenever I try to update a value of core data model. Here is my model

import Foundation import CoreData @objc(Habit) class Habit: NSManagedObject { @NSManaged var name: String @NSManaged var trackingType: NSNumber }

Here is my code tableViewCell

override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if selected { self.accessoryType = UITableViewCellAccessoryType.Checkmark if self.habit? != nil { self.habit?.trackingType = index } } else { self.accessoryType = UITableViewCellAccessoryType.None } // Configure the view for the selected state }

I keep getting error "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Habit setTrackingType:]: unrecognized selector sent to instance 0x7fdcbb002c90'"

at line self.habit?.trackingType = index

I am struggling to fix this for last 2 days.

Edit:

The model habit is initialized in below way

func getHabits() -> [AnyObject]{ let entityDescription = NSEntityDescription.entityForName("Habit", inManagedObjectContext: managedObjectContext!) let request = NSFetchRequest() request.entity = entityDescription // // let pred = NSPredicate(format: "(trackingType != -1)") // request.predicate = pred var error: NSError? var objects = managedObjectContext?.executeFetchRequest(request, error: &error) return objects!; }

The returned list is used everywhere in the app. Basically I fetch and item from the list and update its attributes and then save it again

最满意答案

好的,所以你得到错误的原因当然是因为self.habit引用的对象不是Habit对象。 找出对象真正的最简单方法是调用:

print(NSStringFromClass(habit.class))

使用核心数据和自定义NSManagedObjects您需要确保实体:'Habit'(在您的数据模型中)具有设置为Habit的类。 这可确保Core Data将带有“Habit”实体描述的已获取对象强制转换为Habit类。 如果你不这样做,那么getHabits func将返回一个NSManagedObject数组而不是Habit s数组。如果是这种情况,那么代码: println(NSStringFromClass(habit.class))将打印“NSManagedObject”到调试器。

作为旁注,您确实需要在从Core Data数据库中获取对象时检查错误。 添加行:

if objects? == nil { print("An error occurred \error.localisedDescription") }

如果有任何错误,请原谅我的swift,我通常使用Objective-C。

编辑:为了纠正Failed to call designated initializer on NSManagedObject class 'X'错误Failed to call designated initializer on NSManagedObject class 'X' 。 如果未正确实例化NSManagedObject则会触发此错误。 你不能调用[[MyManagedObject alloc] init]; 你必须调用initWithEntity:insertIntoManagedObjectContext :

MyManagedObject *obj = [[MyManagedObject alloc] initWithEntity:[NSEntityDescription entityForName:@"MyManagedObject" inManagedObjectContext:context] insertIntoManagedObjectContext:context];

如果您不希望将对象obj插入上下文,则可以传递nil上下文参数。 但是,如果您想要撤消管理以及将对象保存到数据库的能力,则需要将其与上下文相关联。

如果要对对象进行自定义初始化,则可以覆盖awakeFromInsert和awakeFromFetch方法/函数。

Ok so the reason you are getting the error is most certainly because the object referenced by self.habit is not a Habit object. The easiest way to find out what the object really is is to call:

print(NSStringFromClass(habit.class))

With core data and custom NSManagedObjects you need to make sure that the entity: 'Habit' (in your data model) has a class set to Habit. This makes sure that Core Data casts your fetched objects with an entity description of 'Habit' to the Habit class. If you are not doing this then the getHabits func will be returning an array of NSManagedObjects not an array of Habits.If this is the case then the code: println(NSStringFromClass(habit.class)) will print "NSManagedObject" to the debugger.

As a side note, you really need to check for errors when you fetch objects from a Core Data database. Add the lines:

if objects? == nil { print("An error occurred \error.localisedDescription") }

Please forgive my swift if there are any errors, I normally use Objective-C.

EDIT: In order to correct Failed to call designated initializer on NSManagedObject class 'X' error. This error is fired when you do not correctly instantiate an NSManagedObject. You must not call [[MyManagedObject alloc] init]; you have to call initWithEntity:insertIntoManagedObjectContext instead:

MyManagedObject *obj = [[MyManagedObject alloc] initWithEntity:[NSEntityDescription entityForName:@"MyManagedObject" inManagedObjectContext:context] insertIntoManagedObjectContext:context];

If you do not want the object obj to be inserted into a context you can pass through a nil context argument. However, if you want undo management and the ability to save the object to the database it needs to be associated with a context.

If you want to have a custom initialisation of an object then you can override the awakeFromInsert and awakeFromFetch methods/functions.

更多推荐

本文发布于:2023-07-28 23:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1310247.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发送到   实例   无法识别   选择器   Coredata

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!