gavsta707 gavsta707 - 3 months ago 9
Swift Question

Issue with setting the text of a TextField with string from NSManagedObject subclass

Description

I am sure I am completely wrong in my line of thinking here, but do correct me. I am simply trying to reference a string I saved in one of my object subclasses. I am doing this by simply trying to set the text of a textField to the string i saved ( on a button click ).

Code

Below you will find the code for my "CrawlerOne+CoreDataProperties.swift" file

import Foundation
import CoreData

extension CrawlerOne {

@nonobjc class func fetchRequest() -> NSFetchRequest<CrawlerOne> {
return NSFetchRequest<CrawlerOne>(entityName: "CrawlerOne");
}

@NSManaged var crawlerAbrasion: String?
@NSManaged var crawlerDistance: String?

}


Here is the part that i am truly just guessing. This code is the "generate" button that is attempting to set the textField to be the string saved

@IBAction func generate(_ sender: AnyObject) {
let appDel:AppDelegate = (UIApplication.shared().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext
let entity1 = NSEntityDescription.insertNewObject(forEntityName:"CrawlerOne", into:context) as NSManagedObject as! CrawlerOne
answer.text = entity1.crawlerAbrasion
}


Finally, here is the code from where I initially saved the String. Note that these two functions are in difference classes & files

@IBAction func save(_ sender: AnyObject) {
let appDel:AppDelegate = (UIApplication.shared().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext
let entity1 = NSEntityDescription.insertNewObject(forEntityName: "CrawlerOne", into:context) as NSManagedObject as! CrawlerOne
entity1.crawlerDistance = distance.text

}


Conclusion

Again, i am absolutely sure that my line of thinking here is just very off, but this is something that i am being pressured to complete very quickly. Also, there is absolutely no errors/messages in regards to this in the Debug Console. I simply click the button to add text to this Textfield and nothing happens. Thank you in advance! :)

Answer

Few things:

  • the property holding the String isn't identical in the generate and save methods
  • not sure if you need to cast to NSManagedObject if CrawlerOne is already an NSManagedObject
  • You are trying to fetch the String by inserting a new object in the managed context, using the result of that operation and therefore setting the label to a text that is nil. You need to create an NSFetchRequest with proper NSPredicates to fetch the original object from your NSManagedContext. You actually have one defined already in your CrawlerOne extension:

class func fetchRequest() -> NSFetchRequest<CrawlerOne>

Now you need to configure it to get the string(s) you are looking for. As mentioned, use NSPredicate for that. There's lots of examples of how to do that, e.g. here.

Comments