Core Data Update in swift while selecting any row in list table view not working?
This line is wrong because you're trying to create an invalid managed object instance:
var managedobjectt = NSManagedObject()
It should be
var managedobjectt : NSManagedObject?
And when you update you aren't changing the current item if it exists, you're just always creating a new instance. You should
if let person = self.managedobjectt {
// update (if anything other than below)
} else {
// create new (insert and set any default values)
}
person.setValue(self.nametextfield.text, forKey: "name")
// save
Update Core Data Object Order - Not Working
Well first of all, you might find it easier to create classes for each entity so that you don't have to work with objects vaguely typed to NSManagedObject
or read and cast with valueForKey(_:)
. In the solution below, I've included code samples for that.
So to solve your order problem, there are two things you could do:
1) Add a property that defines the order of your Task
entity. This can be a simple as an NSNumber
called displayOrder
. Your fetch request can then order the results according to that property. Then, when your table cells are re-arranged, iterate through the task list and update the displayOrder
property of each task to reflect the order in which they are being displayed. Save your managed object context and the next time your fetch request loads, it will order them accordingly.
class Task: NSManagedObject {
@NSManaged var name: NSString
@NSManaged var desc: NSString
@NSManaged var displayOrder: NSNumber
}
let fetchRequest = NSFetchRequest()
let sortDescriptor = NSSortDescriptor(key: "displayOrder", ascending: true )
fetchRequest.sortDescriptors = [ sortDescriptor ]
2) Create a CoreData entity that represents a list with a to-many relationship that stores each task entity in an ordered set. Then, when you add tasks to the set, they will be remain saved in the order you've added them.
class TaskList: NSManagedObject {
@NSManaged var tasks: NSOrderedSet?
}
class Task: NSManagedObject {
@NSManaged var name: NSString
@NSManaged var desc: NSString
@NSManaged var parentList: TaskList?
}
Update to answer remaining questions:
I highly recommend you use your own custom classes instead of NSManagedObject
, but until you figure that part out here's what you can do to your code as is.
To update display order after rearranging or deleting:
func updateDisplayOrder() {
for i in 0..<todayTaskList.count {
let task = todayTaskList[i]
task.setValue( i, forKey: "displayOrder" )
}
}
To append a new task:
func addTask( task: NSManagedObject, displayOrder: Int ) {
todayTaskList.insert( task, atIndex: displayOrder )
updateDisplayOrder()
}
Core Data not fetching in table view
The reason why the entry doesn't show up is that you don't tell the view that your model has changed so it doesn't refresh itself.
The tableView gets rendered once on viewDidLoad
that's why the data is displayed correctly after the view is loaded freshly (after your app restart).
To solve this issue, keep your viewController's tableView as a property (@IBOutlet if you use the Storyboard) and call
tableView.reloadData()
after you changed your data, in your case e.g. at the end of your func showData()
like this.
func showdata() {
guard let appDelage = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelage.persistentContainer.viewContext
let fetchReuqst = NSFetchRequest<NSManagedObject>(entityName: "PersonalInfo")
do {
people = try managedContext.fetch(fetchReuqst)
if people.count == 0 {
//sth
} else {
// sth
}
} catch let err as NSError {
print("judo", err)
}
tableView.reloadData()
}
updating tableview and coredata
Please consolidate your variable names: There are two different data
variables in the loop which causes confusion and the error
Better
for item in result as! [NSManagedObject] {
let data = img!.pngData() as? NSData
item.setValue(data, forKey: "starImage")
}
Nevertheless I recommend to use more specific types and create the image only once
let request = NSFetchRequest<Item>(entityName: "Item")
do {
let result = try context.fetch(request)
let img = UIImage(named: "Gray star icon")
let data = img!.pngData() as? NSData
for item in result {
item.starImage = data
}
} catch {
print("Failed", error)
}
core data fetching int not displaying on tableview cell
Here's why it doesn't work. You have this:
let attr5 = title.value(forKey: "positon") as? String
let text = [" Item :", attr5].compactMap { $0 }.reduce("", +)
This is a really complicated way to try and do this, and it doesn't work as written. The problem is that the value of position
is an Int64
and you need a string. But using as?
like that doesn't turn it into a string. When that line of code runs, Swift says, can I just make this into a string? But it can't. So the as? String
is nil, and your table cells don't include the number because the conversion failed.
A better way would be something like
if let position = title.value(forKey: "positon") {
cell.textLabel?.text = "Item : \(positon))"
}
But that's only if you really want to use value(forKey:)
for some reason. You probably don't need that because normally Xcode creates a subclass of NSManagedObject
for each entity with named properties. So even better would be
cell.textLabel?.text = "Item: \(title.position)"
These both work because string interpolation knows how to convert an integer to a string.
I am using core data. but sequence of data is not maintained (on table view) when I select cell for edit and delete action
Let's break:
models = try context.fetch(ToDoListItem.fetchRequest())
into:
let request = ToDoListItem.fetchRequest()
models = try context.fetch(request)
Now, request
doesn't has a sorting order. If you add a sort, you'll guarantee the order of your items.
It depends on which property you want to sort them, but:
fetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(ToDoListItem.name), ascending: true)]
or
fetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(ToDoListItem.createdAt), ascending: true)]
could be a solution.
Related Topics
Image Disappears When Styling Class to Make a Round Image
How to Display an Image by an API Url? Swift
Unexpected Non-Void Return Value in Void Function Swift 4 Using JSON Serialisation
Swift: How to Get Information for an Application Which Is Not Running
Why Does Function Has Multiple Return Types in Swift
Swift Alamofire Return Value Is Empty
Swift: Can't Edit Properties of Custom Table Cell Programmatically
Comparing Objects in an Array Extension Causing Error in Swift
How to Inject .Environmentobject() in Watchos6
How to Change the Appearance of the Datepicker in the Swiftui Framework to Only Months and Years
How to Call a Func Within a Closure
Ios13 Uialertcontroller with Custom View & Preferredstyle as Actionsheet Grayscale All Colors
Why Does the Compiler Not See the Default Code in a Protocol