I'm having a problem that the sqlite file is only edited when adding the objects in the first time.After that only the sqlite-shm file is changed. So when I relaunch the app nothing changes.Here is the core data stack in the AppDelegate
lazy var managedObjectContext: NSManagedObjectContext = {
let modelURL = NSBundle.mainBundle().URLForResource("StoriesCoreData", withExtension: "mom")
let mom = NSManagedObjectModel(contentsOfURL: modelURL!)
let psc = NSPersistentStoreCoordinator(managedObjectModel: mom!)
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
print (urls[urls.endIndex-1])
let storeURL = (urls[urls.endIndex-1]).URLByAppendingPathComponent("stories.sqlite")
var error: NSError? = nil
var store: NSPersistentStore?
do {
store = try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
} catch var error1 as NSError {
error = error1
store = nil
} catch {
fatalError()
}
if (store == nil) {
print("Failed to load store")
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = psc
return managedObjectContext
}()
func saveContext() {
var error: NSError? = nil
let moc : NSManagedObjectContext? = self.managedObjectContext
if moc == nil {
return
}
if !managedObjectContext.hasChanges {
return
}
do {
try managedObjectContext.save()
return
} catch let error1 as NSError {
error = error1
}
print("Error saving context: \(error?.localizedDescription)\n\(error?.userInfo)")
abort()
}
Here is how the objects are initialized:
let aStory = NSEntityDescription.insertNewObjectForEntityForName("PersonalizedStory", inManagedObjectContext: managedObjectContext) as! PersonalizedStory
aStory.childrenMode = NSNumber(int: 0)
aStory.hidden = NSNumber(int: 0)
aStory.lastEdited = NSDate()
aStory.parentStoryDownloadDate = NSDate()
aStory.parentStoryID = "10000"
aStory.parentWriterID = "guest"
aStory.personalizedStoryID = "10"
aStory.pictureList = []
aStory.userID = "guest"
aStory.inSection = NSSet()
saveContext()
let aSection = NSEntityDescription.insertNewObjectForEntityForName("LibrarySection", inManagedObjectContext: managedObjectContext) as! LibrarySection
aSection.personalizedStoriesOrder = []
aSection.sectionName = "AllStories"
aSection.userID = "guest"
aSection.personalizedStoriesOrder!.append(aStory)
aSection.hasStory = NSSet()
saveContext()
aSection.addObject(aStory, forKey: "hasStory")
aStory.addObject(aSection, forKey: "inSection")
saveContext()
Here is the fetch request and modification:
func allStories () -> [PersonalizedStory]? {
var error : NSError? = nil
let fetchStories = NSFetchRequest(entityName: "LibrarySection")
let sectionsForUser = NSPredicate(format: "userID = %#", argumentArray: [userID])
let all = NSPredicate(format: "sectionName == %#", argumentArray: ["AllStories"])
let fetchPredicates = NSCompoundPredicate(andPredicateWithSubpredicates: [sectionsForUser,all])
fetchStories.predicate = fetchPredicates
var result : [LibrarySection]?
do {
result = try appDelegate.managedObjectContext.executeFetchRequest(fetchStories) as? [LibrarySection]
} catch {
result = nil
}
let theSection = result!.first!.personalizedStoriesOrder!
for story in theSection {
story.setValue(1, forKey: "childrenMode")
}
appDelegate.saveContext()
return theSection
}
So in when I print out the stories later on childMode is set to 1.
However when I relaunch every thing is set back to 0.
And when I check the app folder
Related
I want to pull details from local database but when I do the necessary operations, it returns null as a result. I can't understand where I went wrong.
var chosenCar=""
var chosenCarId : UUID?
the arrays I created, I transfer data to these arrays, there is no problem with that, I did a test
if chosenCar != "" {
//core data
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "CarsInformation")
let idString = chosenCarId?.uuidString
fetchRequest.predicate = NSPredicate(format: "id = %#", idString!)
fetchRequest.returnsObjectsAsFaults = false
do {
let results = try context.fetch(fetchRequest)
if results.count > 0 {
for result in results as! [NSManagedObject] {
if let name = result.value(forKey: "models") as? String {
modelTextField.text = name
}
if let year = result.value(forKey: "year") as? Int {
yearTextField.text = String(year)
}
if let price = result.value(forKey: "price") as? Int {
priceTextField.text = String(price)
}
if let imageData = result.value(forKey: "image") as? Data {
let image = UIImage(data: imageData)
imageView.image = image
}
}
}
} catch{
print("error")
}
} else {
modelTextField.text = ""
priceTextField.text = ""
yearTextField.text = ""
}
After doing these operations, I can't get the result I want.
this is the code how I save images in CoreData:
lazy var dataImage = profileIcon.jpegData(compressionQuality: 1.0)
//MARK: - Saving the Workout Image
func savePUValues() {
// Kontext Identifiziern
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let context = appDelegate.persistentContainer.viewContext
let entityName = "PushUps" //Tabellenname im DatenModell
//Neuen Datensatz anlegen:
guard let newEntity = NSEntityDescription.entity(forEntityName: entityName, in: context)
else {
return
}
let newSet = NSManagedObject(entity: newEntity, insertInto: context)
let savingImage = dataImage
newSet.setValue(savingImage, forKey: "image")
// Datensatz speichern
do {
try context.save()
} catch {
print("An error appeared")
}
}
Now I want to fetch the image data and load it into a UITableView:
With this code:
func loadValues() -> [CellData] {
//Kontext identifizieren
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//Anfrage stellen
let context = appDelegate.persistentContainer.viewContext
let entityName = "PushUps"
//MARK: - Request
// Use a specific fetch request
let request = NSFetchRequest<PushUps>(entityName: entityName)
// add a sort descriptor to sort the items by highScore descending
request.sortDescriptors = [NSSortDescriptor(key: "count", ascending: false)]
do {
// results is an array of PushUps instances, no type cast needed
let results = try context.fetch(request)
for r in results {
if let result = r as? NSManagedObject {
let titletext = "\(count!) Push-Ups"
var cellTitleLabel = UILabel()
cellTitleLabel.text = titletext
let workoutImage = result.value(forKey: "image") as? UIImageView
print("Image was loaded into the array")
var Data1 = CellData(imageData: workoutImage ?? oImageView, titleData: cellTitleLabel)
print("Image: \(String(describing: workoutImage)), TitLe: \(cellTitleLabel) ")
cellDataArray.append(Data1)
}
}
} catch {
print(error)
}
return cellDataArray
}
The problem is that the it's loading the image as nil.
The console is giving me this back: "Image: nil, TitLe: <UILabel: 0x115f17980; frame = (0 0; 0 0); text = '0.0 Push-Ups'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x28249cfa0>> "
So where is the problem? What is wrong with my Code?
Thanks for your help!
The problem is that you are saving Data and trying to retrieve it as a UIImageView, which is doomed to failure:
lazy var dataImage = profileIcon.jpegData(compressionQuality: 1.0)
// Data
let savingImage = dataImage
newSet.setValue(savingImage, forKey: "image")
// still Data
// ---------------------
let workoutImage = result.value(forKey: "image") as? UIImageView
// UIImageView?????
However, don't save image data into Core Data in the first place. Save to disk and store the partial path (e.g. the file name).
I am using this line below :
self.present(activityViewController, animated: true, completion: nil)
And I am getting an error of - Use of unresolved identifier 'self'. Any ideas about how to resolve this? To me it looks as it it is subordinate to the class, but clearly doing something wrong. Any help would be appreciated.
import UIKit
import CoreData
class CoreDataViewController: UIViewController {
#IBOutlet weak var CoreDataView: UITableView!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var items:[Checkins]?
var btnnames = [""]
override func viewDidLoad() {
super.viewDidLoad()
// CoreDataView.dataSource = self
// CoreDataView.delegate = self
storeTranscription()
// Loads the current data
getTranscriptions()
// fetchCheckins()
let btn1name = btnnames[0]
let btn2name = btnnames[1]
let btn3name = btnnames[2]
let btn4name = btnnames[3]
let btn5name = btnnames[4]
let btn6name = btnnames[5]
// print(btnnames)
print(btn1name, btn2name, btn3name, btn4name, btn5name, btn6name)
}
#IBAction func export(_ sender: Any) {
exportDatabase()
}
#IBOutlet weak var Table_label: UILabel!
}
var CheckinDate: Date? = Date()
var fetchedStatsArray: [NSManagedObject] = []
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
func storeTranscription() {
//retrieve the entity that we just created
let entity = NSEntityDescription.entity(forEntityName: "Checkins", in: context)
let transc = NSManagedObject(entity: entity!, insertInto: context) as! Checkins
//set the entity values
transc.who = "Who"
transc.reason = "Reason for visit"
transc.date = CheckinDate
//save the object
do {
try context.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
}
func getTranscriptions () {
//create a fetch request, telling it about the entity
let fetchRequest: NSFetchRequest<Checkins> = Checkins.fetchRequest()
do {
//go get the results
let searchResults = try context.fetch(fetchRequest)
fetchedStatsArray = searchResults as [NSManagedObject]
//I like to check the size of the returned results!
print ("num of results = \(searchResults.count)")
//You need to convert to NSManagedObject to use 'for' loops
for trans in searchResults as [NSManagedObject] {
//get the Key Value pairs (although there may be a better way to do that...
print("\(trans.value(forKey: "who")!)")
let mdate = trans.value(forKey: "CheckinDate") as! Date
print(mdate)
}
} catch {
print("Error with request: \(error)")
}
}
func exportDatabase() {
let exportString = createExportString()
saveAndExport(exportString: exportString)
}
func saveAndExport(exportString: String) {
let exportFilePath = NSTemporaryDirectory() + "Checkins.csv"
let exportFileURL = NSURL(fileURLWithPath: exportFilePath)
FileManager.default.createFile(atPath: exportFilePath, contents: NSData() as Data, attributes: nil)
//var fileHandleError: NSError? = nil
var fileHandle: FileHandle? = nil
do {
fileHandle = try FileHandle(forWritingTo: exportFileURL as URL)
} catch {
print("Error with fileHandle")
}
if fileHandle != nil {
fileHandle!.seekToEndOfFile()
let csvData = exportString.data(using: String.Encoding.utf8, allowLossyConversion: false)
fileHandle!.write(csvData!)
fileHandle!.closeFile()
let firstActivityItem = NSURL(fileURLWithPath: exportFilePath)
let activityViewController : UIActivityViewController = UIActivityViewController(
activityItems: [firstActivityItem], applicationActivities: nil)
activityViewController.excludedActivityTypes = [
UIActivity.ActivityType.assignToContact,
UIActivity.ActivityType.saveToCameraRoll,
UIActivity.ActivityType.postToFlickr,
UIActivity.ActivityType.postToVimeo,
UIActivity.ActivityType.postToTencentWeibo
]
self.present(activityViewController, animated: true, completion: nil)
}
}
func createExportString() -> String {
var checkinwho: String?
var checkinreason: String?
var export: String = NSLocalizedString("who, reason, date \n", comment: "")
for (index, itemList) in fetchedStatsArray.enumerated() {
if index <= fetchedStatsArray.count - 1 {
checkinwho = Checkins.value(forKey: "who") as! String?
checkinreason = itemList.value(forKey: "reason") as! String?
let Datevar = Checkins.value(forKey: "date") as! Date
let whostring = checkinwho
let reasonstring = checkinreason
let DateSting = "\(Datevar)"
export += "\(whostring!),\(reasonstring!),\(DateSting) \n"
}
}
print("This is what the app will export: \(export)")
return export
}
Remove the } on this line
#IBOutlet weak var Table_label: UILabel!
}
and put another } at the end of this file.
I have Int array with values
Example:
var SelectedCard = [Int] ()
[3, 1, 2]
Me need edit my all records by order
Im tried this but app crash
for item in 0...SelectedCard.count-1 {
let order = SelectedCard[item]
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Card")
fetchRequest.predicate = NSPredicate(format: "order == %#", order)
do {
if let fetchResults = try managedContext.fetch(fetchRequest) as? [Card] {
if fetchResults.count != 0 {
for index in 0...fetchResults.count-1 {
let managedObject = fetchResults[index]
managedObject.setValue("", forKey: "folderID")
}
appDelegate.saveContext()
}
}
} catch {
print(error)
}
}
self.tableView.reloadData()
Try changing the predicate to
NSPredicate(format: "order == \(order)")
good morning all together,
i would like to request all data of my coredata where the name field is "meyer"
at the moment, i do it like this way, but i think, this is not the best way to do this.
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var lebensmittel = [LM_ITEMS]()
var LM_ITEM:NSManagedObject!
var x :Int = 0
var NumberOfLM :Int = 0
func DatenAbrufen() {
let fetchRequest = NSFetchRequest(entityName: "LM_ITEMS")
if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [LM_ITEMS] {
lebensmittel = fetchResults
while x < fetchResults.count {
var TEMP_LM_ITEM = lebensmittel[x]
if TEMP_LM_ITEM.name == "meyer" {
LM_ITEM = lebensmittel[x]
NumberOfLM++
}
x++
}
}
LebensmittelTable.reloadData()
}
Use a predicate with your NSFetchRequest instead of looping:
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
var lebensmittel = [LM_ITEMS]()
func DatenAbrufen() {
var fetchRequest = NSFetchRequest(entityName: "LM_ITEMS")
fetchRequest.predicate = NSPredicate(format: "name = %#", "meyer")
if let fetchResults = managedObjectContext.executeFetchRequest(fetchRequest, error: nil) as? [LM_ITEMS] {
lebensmittel = fetchResults
}
LebensmittelTable.reloadData()
}