I have a class with a parameter in the form
class class_name: Codable {
var array_name = []
}
Running the code, I see I can add numbers in the array. But when I get the array in another function it says it is empty. I do it with:
let new_class = class_name()
Can it happen that the value gets reseted for calling the class again?
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I have the model that the images show. In the entity Word I have the attribute name, that I want to be constraint. If I don't make it constraint the model works perfectly, but when I make it constraint it crashes just when opening giving this error. The only code it reads is a DataController in which I just create the container and set mergePolicy to NSmergeByPropertyObjectTrumpMergePolicy.
I think I need name in Word to be constraint. Otherwise when deleting or adding relations with train_list or test_list I get many words with the same name, when I just want one that is added or deleted from these lists.
I don't really know what are the requirements to use a constraint. Maybe there is a conflict with the relationships I have or the delete rules. Any idea?
I have a relation between 2 objects that works fine. I create it and then I try to fetch one object from the other object (with the relation) and it works. But after a certain time this relation stops working and trying to get one object from the other gives mean error (with exactly the same code). I'm trying to see where this happens exactly but there isn't a particular part of the code where this relation is forgotten. Sometimes is in one line and sometimes in another different line.
The relations are shown in the image. The entities that I'm using are TopicData and WordData, so just a one-to-many relation.
I have no constraint attributes and codegene for all entities is Manual/None. After finishing the core data file, I have created NSManagedObject subclasses for all the entities. And in these subclasses I have added some functions to fetch objects.
My question is why could it happen that relations disappear. I wonder if it could be related to the core data codegen and creating my own functions inside those subclasses.
As an example, here is the code of the generated subclass GroupData+CoreDataProperties, where I added my own functions. The function getTopicFromGroup is the one that works fine first but then crashes (there isn't a topic for the group)
import Foundation
import CoreData
extension GroupData {
@nonobjc public class func fetchRequest() -> NSFetchRequest<GroupData> {
return NSFetchRequest<GroupData>(entityName: "GroupData")
}
static func getGroupFromIndexAndTopic(index: Int16, topic: TopicData, context:NSManagedObjectContext) -> GroupData {
let fetchRequest = NSFetchRequest<GroupData>(entityName: "GroupData")
fetchRequest.predicate = NSPredicate(format: "index_group = %d AND topic = %@", index, topic)
let groups = (try? context.fetch(fetchRequest)) ?? []
let group = groups.first!
return group
}
@NSManaged public var cleared_words: Int16
@NSManaged public var index_group: Int16
@NSManaged public var mean_level: Int16
@NSManaged public var topic: TopicData?
@NSManaged public var word: NSSet?
}
// MARK: Generated accessors for word
extension GroupData {
@objc(addWordObject:)
@NSManaged public func addToWord(_ value: Word)
@objc(removeWordObject:)
@NSManaged public func removeFromWord(_ value: Word)
@objc(addWord:)
@NSManaged public func addToWord(_ values: NSSet)
@objc(removeWord:)
@NSManaged public func removeFromWord(_ values: NSSet)
}
extension GroupData : Identifiable {
}
And the function GroupData+CoreDataClass is like it was created, I didn't add anything
import Foundation
import CoreData
@objc(GroupData)
public class GroupData: NSManagedObject {
}
I'm finding this issue after making sure I create an entity with the correspondent attribute.
This issue comes from a relation between 2 entities: GroupData and TopicData. Their relations are like shown in the screenshots.
Then, I get the context from a function like the next one. Every time I need to use the context, I call this function.
import CoreData
class DataController: ObservableObject {
let container = NSPersistentContainer(name: "vocabul-R")
init() {
container.loadPersistentStores { description, error in
if let error = error {
print("CoreData failed to load: \(error.localizedDescription)")
}
}
container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
container.viewContext.retainsRegisteredObjects = true
}
}
I first create the objects from data I get from csv files. By debugging I've made sure that the objects created have the correspondent values for each attribute and the correct objects in relations.
guard let filepath = Bundle.main.path(forResource: data_file, ofType: "csv") else {
return
}
let dataController = DataController()
let context = dataController.container.viewContext
do {
try context.save()
}
catch {
}
var data = ""
do {
data = try String(contentsOfFile: filepath)
} catch {
return
}
var rows = data.components(separatedBy: "\n")
rows.remove(at: 0)
for row in rows {
let columns = row.components(separatedBy: ",")
let name = columns[0]
let activation_level = (columns[1] as NSString).integerValue
let activated: Bool = false
let last_opened_group: Int16 = 0
let current_level: Int16 = 0
let topic = TopicData(context: context)
topic.name = name
topic.activated = activated
topic.activationLevel = Int16(activation_level)
topic.last_opened_group = last_opened_group
topic.current_level = current_level
do {
try context.save()
}
catch {
print("Context not saved")
}
}
}
func parseCSV_groups (data_file: String, topic_name: String) {
guard let filepath = Bundle.main.path(forResource: data_file, ofType: "csv") else {
return
}
var data = ""
do {
data = try String(contentsOfFile: filepath)
} catch {
return
}
var rows = data.components(separatedBy: "\n")
rows.remove(at: 0)
let dataController = DataController()
let context = dataController.container.viewContext
let topic = TopicData.getTopicFromName(name: topic_name, context: context)
let train_list = Train_list(context: context)
let test_list = Test_list(context: context)
train_list.train_list = "train_list"
test_list.test_list = "test_list"
for row in rows {
let columns = row.components(separatedBy: ",")
let index_group = (columns[0] as NSString).integerValue
let mean_level = (columns[1] as NSString).integerValue
let cleared_words: Int16 = 0
let group = GroupData(context: context)
group.index_group = Int16(index_group)
group.mean_level = Int16(mean_level)
group.cleared_words = cleared_words
//group.topic = topic
topic.addToGroup(group)
do {
try context.save()
}
catch {
print("Context not saved")
}
}
}
I have created objects from both entities with relations. I have other functions with relations between these and other entities seem to work fine. But now I need to get all the groups that one TopicData object has. For that, I first get a topic from its name.
let fetchRequest = NSFetchRequest<TopicData>(entityName: "TopicData")
fetchRequest.predicate = NSPredicate(format: "name = %@", name)
let topics = (try? context.fetch(fetchRequest)) ?? []
let topic = topics.first ?? TopicData()
return topic
}
This seems to work fine as I can print the topic name and the object type (which is TopicData). But then I try to get the groups that it has.
I've also tried to get the groups with a fetchRequest
/fetchRequest.predicate = NSPredicate(format: "topic = %@", topic)
let groups = (try? context.fetch(fetchRequest)) ?? []
And when I try to get one of the attributes (activated) of one of these topics, I also get an error.
I thought this could be happening because every time I use a topic to update it and save it on context again, a new topic is created which may not be related to GroupData. But I added a constraint in TopicData for name and I still get the same error.
Another thing I thought is that relations could be disappearing, since I saw some people had this problem and the issue was that. But I added the retainsRegisteredObjects line in DataController and it didn't work.
The full error I get is:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TopicData group]: unrecognized selector sent to instance 0x600003812bc0'
terminating with uncaught exception of type NSException
I think that is all about the problem. Any idea of what could be happening? I think I added everything relevant for the problem, but let me know if there is some other code I should add. Thank you!
I'm getting this error because it seems the database forgets objects relations. I always use the same context (with different instances on each function), so I think I can't do anything with mutableSetValue. Also, I've tried to set retainsRegisteredObjects, but it doesn't seem to improve anything.
An option I was thinking about is always using the same context and send it from one function to the next one, but it doesn't feel like that's an optimal solution. And I'm not sure if relations would stay after I closed the app, which is something I need.
Any ideas of how to solve this issue?
I have 3 entities: Topic, Group and Word. Topic has a one-to-many relation with Group, and Group has a one-to-many relation with Word. From a list of words, I want to get the ones that belong to certain topic. That means, getting the group of the word and then the topic of the word.
For a Word fetch request, I have NSPredicate(format: "group.topic = %@", topic). Where topic is the object I want to match word to. But this isn't working so I guess it isn't the right way of doing it.
Does someone know how something like this could be done?
I'm having problems with NSPredicate. It started because for some conditions I got empty lists when I knew there was something in the model.
I've made a lot of tests and I found that it fails when I use %@ (to have a variable). If I write the variable directly, it works fine. But in some situations, it works fine when I have a %@, but if I add a second variable with AND it gives again an empty list. I've checked that the context, the spelling are fine. Also, the objects do exist, since I get them by typing the variable directly. For some reason, I get an empty list in some situation (which are always the same situations, it doesn't happen randomly).
I think the problem is that CoreData gives and error, so I get an empty list as the default. Does anyone know what could be happening?