Post

Replies

Boosts

Views

Activity

How to Resolve Swift 5 error: "Cannot Call value of non-function type '[String]'
Hello:I have been struggling with this small piece of code foe days. Every time I resolve one problem with it, another one pops up:I seem to have resolved the problem of "Expected Pattern" but now I have the problem "Cannot call value of non-function type '[String]'Here is the code:var name = [String]() override func viewDidLoad() { super.viewDidLoad() let persistentContainer = NSPersistentContainer(name: "No_Regrets") persistentContainer.loadPersistentStores { (_, error) in if let error = error { fatalError("Failed to load Core Data stack: \(error)") } } // Creates a task with a new background context created on the fly persistentContainer.performBackgroundTask { (context) in //iterates the array let Gains = [self.gain1, self.gain2, self.gain3, self.gain4] Gains.forEach {_ in // Creates a new entry inside the context `context` and assign the array element `name` to the dog's name let gain1 = Gains(context: context) //Cannot call value of non-function type '[String]' gain1.name = name let gain2 = Gains(context: context) //Cannot call value of non-function type '[String]' gain2.name = name let gain3 = Gains(context: context) //Cannot call value of non-function type '[String]' gain3.name = name let gain4 = Gains(context: context) //Cannot call value of non-function type '[String]' gain4.name = name } do { // Saves the entries created in the `forEach` try context.save() } catch { fatalError("Failure to save context: \(error)") } }
2
1
3.2k
Jun ’19
How to transfer fetched Results from CoreData managedContext to a backgroundContext
Hello:I have successfully fetched data from an entity in my CoreData store "SCQ". I am able to use the data with all properties. Now I want to move that fetched data to a backgroundContext and save it to a new entity in the CoreData store "TempSCQ". When I try to save no data is available.Any help will be appreciated.Here is my code:guardlet appDelegate = NSApplication.shared.delegate as? AppDelegate else { return } // print ("Step Four") _ = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest(entityName: "SCQ") fetchRequest.returnsObjectsAsFaults = false // And Predicate let predicate1 = NSPredicate(format: "grade = %@",nameGrade) let predicate2 = NSPredicate(format: "qid = %i", count) fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate1,predicate2]) do { items = try managedContext.fetch(fetchRequest) print ("Records fetched is \(count)" ) print ("selected grade is \(nameGrade)") print ("Number is \(count)") print ("Group Name is \(nameGroup)") } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } let backgroundContext = persistentContainer.newBackgroundContext () // var saveItems = NSEntityDescription.insertNewObject(forEntityName: "SCQ", into: backgroundContext) persistentContainer.viewContext.automaticallyMergesChangesFromParent = true let entity = NSEntityDescription.entity(forEntityName: "TempSCQ", in: backgroundContext)! let component = NSManagedObject(entity: entity, insertInto: backgroundContext) for item in items { if let record = item.value(forKey: "answer") as? String { answerItem.append(record) } if let record = item.value(forKey: "difficultyLevel") as? String { difficultyLevelItem.append(record) } if let record = item.value(forKey: "dictractor1") as? String { distractor1Item.append(record) } if let record = item.value(forKey: "dictractor2") as? String { distractor2Item.append(record) } if let record = item.value(forKey: "dictractor3") as? String { distractor3Item.append(record) } if let record = item.value(forKey: "dictractor4") as? String { distractor4Item.append(record) } if let record = item.value(forKey: "dictractor5") as? String { distractor5Item.append(record) } if let record = item.value(forKey: "grade") as? String { gradeItem.append(record) } if let record = item.value(forKey: "id") as? String { idItem.append(record) } if let record = item.value(forKey: "qid") as? String { qidItem.append(record) } if let record = item.value(forKey: "question") as? String { questionItem.append(record) } if let record = item.value(forKey: "qValue") as? String { qValueItem.append(record) } if let record = item.value(forKey: "skill") as? String { skillItem.append(record) } if let record = item.value(forKey: "subject") as? String { subjectItem.append(record) } if let record = item.value(forKey: "topic") as? String { topicItem.append(record) } do { try backgroundContext.save() items.append (component) print("saved") } catch { } }Here are the debug results:Records fetched is 397selected grade is 8Number is 397Group Name is ScorCentCoreData: sql: INSERT INTO ZTEMPSCQ(Z_PK, Z_ENT, Z_OPT, ZANSWER, ZDIFFICULTYLEVEL, ZDISTRACTOR1, ZDISTRACTOR2, ZDISTRACTOR3, ZDISTRACTOR4, ZDISTRACTOR5, ZGRADE, ZID, ZQVALUE, ZQID, ZQUESTION, ZSKILL, ZSUBJECT, ZTOPIC) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)CoreData: details: SQLite bind[0] = (int64)5CoreData: details: SQLite bind[1] = (int64)9CoreData: details: SQLite bind[2] = (int64)1CoreData: details: SQLite bind[3] = nilCoreData: details: SQLite bind[4] = nilCoreData: details: SQLite bind[5] = nilCoreData: details: SQLite bind[6] = nilCoreData: details: SQLite bind[7] = nilCoreData: details: SQLite bind[8] = nilCoreData: details: SQLite bind[9] = nilCoreData: details: SQLite bind[10] = nilCoreData: details: SQLite bind[11] = nilCoreData: details: SQLite bind[12] = nilCoreData: details: SQLite bind[13] = nilCoreData: details: SQLite bind[14] = nilCoreData: details: SQLite bind[15] = nilCoreData: details: SQLite bind[16] = nilCoreData: details: SQLite bind[17] = nilCoreData: sql: COMMITCoreData: sql: pragma page_countCoreData: annotation: sql execution time: 0.0000sCoreData: sql: pragma freelist_countCoreData: annotation: sql execution time: 0.0000sCoreData: sql: pragma incremental_vacuum(25)CoreData: annotation: sql execution time: 0.0002ssaved
0
0
410
Sep ’19
Not Loading NSPopupbutton. Why?
Hello: I am trying to load an NSPopupButton from a property list, but running the code below results in a fatal error: "Unexpectedly found nil while implicitly unwrapping an Optional value" on line i4. The debug output shows the following:figures count 4viewDidLoad() figures count 4Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file /Users/wlionelwilliams/Desktop/ScorcentMasterReview/ScorcentMasterReview/FiguresViewController.swift, line 109Line 10 seems to suggest that the items for the Popupbutton list is available. What am I missing?overridefunc viewDidLoad() { super.viewDidLoad() if let filePath = Bundle.main.path(forResource: "TFigures", ofType: "plist") { print("filePath", filePath) figures = Figure.figuresList(filePath) print("figures count", figures.count) } // figuresButton.removeAllItems() print(#function, "figures count", figures.count) for figure in figures { figuresButton.addItem(withTitle:figure.title) } print ("itemsCount", title!.count) selectedFigure = figures [0] figuresButton.selectItem(at: 0) }
11
0
962
Nov ’19
How to Clear UI contents after each function call
Hello:I have a function which when called, populates the labels and textView with data from a CoreData Fetch Request, for the user. Each time the function is called I want ONLY the new data in the UI controls. Presently, the new data is appended to the old which is totally unacceptable.How can I clear the old data so that the User sees ONLY the new data?Thanks for helping me with the solution.
7
0
526
Dec ’19
How to Use textField input in a fetchRequest predicate
Hello:I am trying to use textfield input in a fetchRequest predicate as follows:@IBOutlet weak var gradeValue: NSTextField! @IBAction func saveNameGrade(_ sender: Any) { gradeValue.stringValue = nameGrade }I want to use the value entered in the text field (gradeValue) and save it in the variable "nameGrade" then use "nameGrade" as the Predicate in my fetchRequest like so:let predicate2 = NSPredicate(format: "grade = %@",nameGrade) print ("selected grade is \(nameGrade)")// returns nilBut this doesn't work.Any help will be appreciated.
1
0
391
Dec ’19
How to save fetched results to a different CoreData entity with same properties
Hello:I have successfully fetched data from an entity in my CoreData store "SCQ". I am able to use the data with all properties. Now I want to move that fetched data to a backgroundContext and save it to a new entity in the CoreData store "TempSCQ". When I try to save no data is available.Any help will be appreciated.Here is my code:guardlet appDelegate = NSApplication.shared.delegate as? AppDelegate else { return } // print ("Step Four") _ = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest(entityName: "SCQ") fetchRequest.returnsObjectsAsFaults = false // And Predicate let predicate1 = NSPredicate(format: "grade = %@",nameGrade) let predicate2 = NSPredicate(format: "qid = %i", count) fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate1,predicate2]) do { items = try managedContext.fetch(fetchRequest) print ("Records fetched is \(count)" ) print ("selected grade is \(nameGrade)") print ("Number is \(count)") print ("Group Name is \(nameGroup)") } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } let backgroundContext = persistentContainer.newBackgroundContext () // var saveItems = NSEntityDescription.insertNewObject(forEntityName: "SCQ", into: backgroundContext) persistentContainer.viewContext.automaticallyMergesChangesFromParent = true let entity = NSEntityDescription.entity(forEntityName: "TempSCQ", in: backgroundContext)! let component = NSManagedObject(entity: entity, insertInto: backgroundContext) for item in items { if let record = item.value(forKey: "answer") as? String { answerItem.append(record) } if let record = item.value(forKey: "difficultyLevel") as? String { difficultyLevelItem.append(record) } if let record = item.value(forKey: "dictractor1") as? String { distractor1Item.append(record) } if let record = item.value(forKey: "dictractor2") as? String { distractor2Item.append(record) } if let record = item.value(forKey: "dictractor3") as? String { distractor3Item.append(record) } if let record = item.value(forKey: "dictractor4") as? String { distractor4Item.append(record) } if let record = item.value(forKey: "dictractor5") as? String { distractor5Item.append(record) } if let record = item.value(forKey: "grade") as? String { gradeItem.append(record) } if let record = item.value(forKey: "id") as? String { idItem.append(record) } if let record = item.value(forKey: "qid") as? String { qidItem.append(record) } if let record = item.value(forKey: "question") as? String { questionItem.append(record) } if let record = item.value(forKey: "qValue") as? String { qValueItem.append(record) } if let record = item.value(forKey: "skill") as? String { skillItem.append(record) } if let record = item.value(forKey: "subject") as? String { subjectItem.append(record) } if let record = item.value(forKey: "topic") as? String { topicItem.append(record) } do { try backgroundContext.save() items.append (component) print("saved") } catch { } }Here are the debug results:Records fetched is 397selected grade is 8Number is 397Group Name is ScorCentCoreData: sql: INSERT INTO ZTEMPSCQ(Z_PK, Z_ENT, Z_OPT, ZANSWER, ZDIFFICULTYLEVEL, ZDISTRACTOR1, ZDISTRACTOR2, ZDISTRACTOR3, ZDISTRACTOR4, ZDISTRACTOR5, ZGRADE, ZID, ZQVALUE, ZQID, ZQUESTION, ZSKILL, ZSUBJECT, ZTOPIC) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)CoreData: details: SQLite bind[0] = (int64)5CoreData: details: SQLite bind[1] = (int64)9CoreData: details: SQLite bind[2] = (int64)1CoreData: details: SQLite bind[3] = nilCoreData: details: SQLite bind[4] = nilCoreData: details: SQLite bind[5] = nilCoreData: details: SQLite bind[6] = nilCoreData: details: SQLite bind[7] = nilCoreData: details: SQLite bind[8] = nilCoreData: details: SQLite bind[9] = nilCoreData: details: SQLite bind[10] = nilCoreData: details: SQLite bind[11] = nilCoreData: details: SQLite bind[12] = nilCoreData: details: SQLite bind[13] = nilCoreData: details: SQLite bind[14] = nilCoreData: details: SQLite bind[15] = nilCoreData: details: SQLite bind[16] = nilCoreData: details: SQLite bind[17] = nilCoreData: sql: COMMITCoreData: sql: pragma page_countCoreData: annotation: sql execution time: 0.0000sCoreData: sql: pragma freelist_countCoreData: annotation: sql execution time: 0.0000sCoreData: sql: pragma incremental_vacuum(25)CoreData: annotation: sql execution time: 0.0002ssaved
4
0
758
Dec ’19
Not able to save to Core Data. Why?
Hello:I have the below code. I am trying to save values from the backgroundContext "Items" to the column "answer" (I come from an Oracle background) in Core Data. Line 21 shows that the variable "answerItem" has the correct data for each loop but when I check the Data Store the "answer" column is blank.Any help will be appreciates to edit the code so that the data will be saved.let backgroundContext = persistentContainer.newBackgroundContext () persistentContainer.viewContext.automaticallyMergesChangesFromParent = true let entity = NSEntityDescription.entity(forEntityName: "TempSCQ", in: backgroundContext)! var answerItem: String = "" for item in items { answerItem = "" let newEntity = NSManagedObject(entity: entity, insertInto: backgroundContext) if let record = item.value(forKeyPath: "answer") as? String { newEntity.setValue(answerItem, forKey: "answer") answerItem.append(record) print ("Answer Item is \(answerItem)") print ("PProcess E1") } do { try backgroundContext.save() // print("saved") } catch { } } } }
2
0
486
Dec ’19
Bad Code
Hello: I have the code below to try to get a random selection from CoreData store. However i'm getting a crash on line 33 with the error:Thread 1: EXC_BAD_ACCESS (code=1, address=0x232). After studying the code for hours, I still can't figure out why the crash. The code actually worked one time!!!let fetchRequest = NSFetchRequest(entityName: "TempSCQ") fetchRequest.includesPropertyValues = false var selector = Int() nameGrade = gradeValue.stringValue print ("Grade entered is \(nameGrade)") func getRandomRecord () { if nameGrade == "2" { selector = Int.random(in: 0 ..< 355) } else if nameGrade == "4" { selector = Int.random(in: 0 ..< 418) } else if nameGrade == "6" { selector = Int.random(in: 0 ..< 375) } else if nameGrade == "8" { selector = Int.random(in: 0 ..< 813) } else if nameGrade == "12" { selector = Int.random(in: 0 ..< 355) } } getRandomRecord() fetchRequest.predicate = NSPredicate(format: "qid == %@", selector) //Thread 1: EXC_BAD_ACCESS (code=1, address=0x232)
2
0
616
Dec ’19
How to get Random number from variable
Hello:I have the following scenario:Using NSFetchRequest i get a count of items returned as:numberRecords = items.countI want to get a random record based on the number of records in "numberRecords".Now i can get a random value using : selector = Int.random(in: 0 ..< 355)But how can I use "numberRecords" to get a numerical value?Thanks.
7
0
960
Dec ’19
How to find sum of values in Variables
Hello:I am fetching records from CoreData in which there is an item called QValue. qValue is defined as a String but it has a number.qValue has different values (1000,1450, 1830, etc.)Each time the user calls for a record it returns a qValue in the data set.I want to Sum all the qValues returned in a session.I have tried many different ways but without success: for example (The error here is "Ambiguous reference to member '+' ")if let record = item.value(forKey: "qValue") as? String { qValueItem.append(record) groupScoreLabel.stringValue = qValueItem print ("qValue is \(qValueItem)") } if (oneRadioButton.state == NSControl.StateValue(rawValue: 1)) && distractor1 == answerItem { let arr = [qValueItem] let totalSum = arr.reduce(0, +) // Ambiguous reference to member '+' print("totalSum \(totalSum)")I want an increasing value with each record call which will be the "totalSum"Any help with implementing will be appreciated.
12
0
717
Dec ’19
Radio Buttons not Working
Hello I am trying to implement use of Radio buttons. After days of trying to get the values of my radio buttons (that is to see which one is checked and save value) I have had no success:Here is my code:var qValueNumbers = [0] let totalSum = Int() @IBAction func calcGroupScore(_ sender: NSButton) { answerItem = "" for item in results { if let record = item.value(forKey: "answer") as? String { answerItem.append(record) answerLabel.stringValue = answerItem print ("Answer is \(answerItem)") if let record = item.value(forKey: "qValue") as? String, var theValue = Int(record) { // groupScoreLabel.stringValue = qValueItem print ("qValueNumbers before append", qValueNumbers) func getScore (){ if (oneRadioButton != nil) && distractor1 == answerItem { print("button1 Selected") qValueNumbers.append(theValue) } if (twoRadioButton != nil) && distractor2 == answerItem { print("button2 Selected") qValueNumbers.append(theValue) } if (threeRadioButton != nil) && distractor3 == answerItem { print("button3 Selected") qValueNumbers.append(theValue) } if (fourRadioButton != nil) && distractor4 == answerItem { print("button4 Selected") qValueNumbers.append(theValue) } if (fiveRadioButton != nil) && distractor5 == answerItem { print("button5 Selected") qValueNumbers.append(theValue) } else{ // qValueNumbers.append(0) print ("The value of qValue is \(theValue)") } } getScore() qValueNumbers.append(theValue) let totalSum = qValueNumbers.reduce(0, +) print ("qValue is \(theValue)") print ("qValueNumbers after append", qValueNumbers) print ("Total is \(totalSum)") print ("Group score is \(totalSum)") } } }Here is my log output:Answer is 3qValueNumbers before append [0, 1530, 2650]The value of qValue is 2650qValue is 2650qValueNumbers after append [0, 1530, 2650, 2650]Total is 6830Group score is 6830Here is the problem:Whether or not a button is selected the "qValue" is still appended to qValueNumbers". If a radio button between 1 and 5 is selected and that button is the correct answer, then the qValue should be appended. As of now regardless of whether the checked button matches the correct answer a qValue is still appended instead of "0".Any help will nbe appreciated.
6
0
1.7k
Dec ’19
Core Data Error with NSDate
hello:Can someone tell me why I am getting a crash when saving a date attribute in Core Data:Unacceptable type of value for attribute: property = "date"; desired type = NSDate; given type = NSDate; value = NSDate.let date = NSDate() . . . let groupObject = NSEntityDescription.insertNewObject(forEntityName: "GroupRecord", into: managedContext) groupObject.setValue(NSDate.self, forKeyPath: "date")// crash occurs heredo { try managedContext.save()
6
0
1.8k
Dec ’19
Text Field stringValue saves twice in CoreData. Why?
Hello:I have the following code: There are no build errors, But the first text field "groupName" saves immediately (even without pressing the enter key) when I move to the next field, before the rest of the fields are entered. Then saves again when I press the SAVE button. That does not happen with any of the other three fields.Any help with identifying why that happesn will be appreciated.import Cocoa import CoreData class GroupViewController: NSViewController { var items: [NSManagedObject] = [] override func viewDidLoad() { super.viewDidLoad() } @IBOutlet weak var groupNameTextField: NSTextField! @IBOutlet weak var memberOneTextField: NSTextField! @IBOutlet weak var memberTwoTextField: NSTextField! @IBOutlet weak var memberThreeTextField: NSTextField! @IBAction func saveGroup(_ sender: Any) { print("SAVE ACTION STARTED") let appDelegate = NSApplication.shared.delegate as! AppDelegate let managedContext = appDelegate.persistentContainer.viewContext let registerStudentsObject = NSEntityDescription.insertNewObject(forEntityName: "PlayerGroups", into: managedContext) print("MOC READ") registerStudentsObject.setValue(groupNameTextField.stringValue, forKey: "groupName") registerStudentsObject.setValue(memberOneTextField.stringValue, forKey: "name1") registerStudentsObject.setValue(memberTwoTextField.stringValue, forKey: "name2") registerStudentsObject.setValue(memberThreeTextField.stringValue, forKey: "name3") print("FIELDS READ") do { try managedContext.save() items.append (registerStudentsObject) print("groupName, name1, name2, name3 saved") } catch { print (error) } } }Here is the output log:SAVE ACTION STARTEDCoreData: annotation: Connecting to sqlite database file at "/Users/wlionelwilliams/Library/Containers/AppDev.ScorcentMasterReview/Data/Library/Application Support/ScorcentMasterReview/ScorcentMasterReview.sqlite"CoreData: sql: SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'Z_METADATA'CoreData: sql: pragma recursive_triggers=1CoreData: sql: pragma journal_mode=walCoreData: sql: SELECT Z_VERSION, Z_UUID, Z_PLIST FROM Z_METADATACoreData: sql: SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'Z_METADATA'CoreData: sql: SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'Z_MODELCACHE'CoreData: sql: SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'ACHANGE'CoreData: sql: SELECT TBL_NAME FROM SQLITE_MASTER WHERE TBL_NAME = 'ATRANSACTIONSTRING'MOC READFIELDS READCoreData: sql: BEGIN EXCLUSIVECoreData: sql: SELECT Z_MAX FROM Z_PRIMARYKEY WHERE Z_ENT = ?CoreData: annotation: getting max pk for entityID = 4CoreData: sql: UPDATE OR FAIL Z_PRIMARYKEY SET Z_MAX = ? WHERE Z_ENT = ? AND Z_MAX = ?CoreData: annotation: updating max pk for entityID = 4 with old = 26 and new = 27CoreData: sql: pragma auto_vacuumCoreData: annotation: sql execution time: 0.0000sCoreData: sql: pragma auto_vacuum=2CoreData: annotation: sql execution time: 0.0000sCoreData: sql: COMMITCoreData: sql: BEGIN EXCLUSIVECoreData: sql: INSERT INTO ZPLAYERGROUPS(Z_PK, Z_ENT, Z_OPT, ZGROUPNAME, ZNAME1, ZNAME2, ZNAME3) VALUES(?, ?, ?, ?, ?, ?, ?)CoreData: details: SQLite bind[0] = (int64)27CoreData: details: SQLite bind[1] = (int64)4CoreData: details: SQLite bind[2] = (int64)1CoreData: details: SQLite bind[3] = "SCORCENT"CoreData: details: SQLite bind[4] = ""CoreData: details: SQLite bind[5] = ""CoreData: details: SQLite bind[6] = ""CoreData: sql: COMMITCoreData: sql: pragma page_countCoreData: annotation: sql execution time: 0.0000sCoreData: sql: pragma freelist_countCoreData: annotation: sql execution time: 0.0000sgroupName, name1, name2, name3 savedSAVE ACTION STARTEDMOC READFIELDS READCoreData: sql: BEGIN EXCLUSIVECoreData: annotation: getting max pk for entityID = 4CoreData: annotation: updating max pk for entityID = 4 with old = 27 and new = 28CoreData: sql: COMMITCoreData: sql: BEGIN EXCLUSIVECoreData: sql: INSERT INTO ZPLAYERGROUPS(Z_PK, Z_ENT, Z_OPT, ZGROUPNAME, ZNAME1, ZNAME2, ZNAME3) VALUES(?, ?, ?, ?, ?, ?, ?)CoreData: details: SQLite bind[0] = (int64)28CoreData: details: SQLite bind[1] = (int64)4CoreData: details: SQLite bind[2] = (int64)1CoreData: details: SQLite bind[3] = "SCORCENT"CoreData: details: SQLite bind[4] = "John Doe"CoreData: details: SQLite bind[5] = "Jane Doe"CoreData: details: SQLite bind[6] = "Peter Pan"CoreData: sql: COMMITgroupName, name1, name2, name3 saved
1
0
710
Dec ’19
How to populate NSTableView with NSFetchResultsController
Hello:I've been studying up on How to populate an NSTableView with data from CoreData using a fetchRequest. A lot of the information I found is for Swift 3 and 4. I am using the latest Xcode Version with Swift 5.1. I've looked at the Apple Documentation, lots of tutorials, some responses in Apple CoreData Forum, and my implementation of tableViews with CoreData in my iOS app.Using what I've found, I constructed the code below to be able to display data from my CoreData store in an NSTableView (MAC OSx app).I set up the NSTableView inside of a ViewController, added the delegates, set the cell identifiers in interface builder, and setup for three columns.I think that what I've done below is too much (It absolutely can't be "not enough"). In any case , no data is displayed in the table View.I'd really appreciate some help with this.Thanks in advance. Please let me know what I don't need.import Cocoa import CoreData class RegistrationReportsViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() showRegisteredStudents() tableView.dataSource = self as? NSTableViewDataSource tableView.delegate = self as? NSTableViewDelegate } private lazy var fetchedResultsController: NSFetchedResultsController = { let fetchRequest: NSFetchRequest = Registration.fetchRequest() let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil) frc.delegate = self return frc }() var managedObjectContext = (NSApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "ScorcentMasterReview") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error { fatalError("Unresolved error \(error)") } }) return container }() @IBOutlet weak var tableView: NSTableView! func showRegisteredStudents() { guard (NSApplication.shared.delegate as? AppDelegate) != nil else { return } let managedContext = (NSApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let fetchRequest = NSFetchRequest(entityName: "Registration") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "lastName", ascending: true)] do { let records = try managedContext.fetch(fetchRequest) as! [NSManagedObject] print ("There are \(records.count) records") let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil) // Configure Fetched Results Controller fetchedResultsController.delegate = self print("First Name is \(records)") self.tableView.reloadData() return() } catch { fatalError("Failed to fetch employees: \(error)") } func controllerWillChangeContent(_ controller: NSFetchedResultsController) { tableView.beginUpdates() } func controllerDidChangeContent(_ controller: NSFetchedResultsController) { tableView.endUpdates() } } } var records: [NSManagedObject] = [] extension RegistrationReportsViewController : NSTableViewDataSource{ func numberOfRows(in tableView: NSTableView) -> Int{ return records.count } } extension RegistrationReportsViewController : NSTableViewDelegate{ fileprivate enum CellIdentifiers { static let lastNameCell = "LNCellID" static let firstNameCell = "FNCellID" static let middleNameCell = "MNCellID" } //NSTableViewDelegate func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let cell: NSTableCellView! let column = tableView.tableColumns.firstIndex(of: tableColumn!)! switch column { case 0: cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "lastName"), owner: nil) as? NSTableCellView case 1: cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "firstName"), owner: nil) as? NSTableCellView case 2: cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "middleName"), owner: nil) as? NSTableCellView default: return nil } configureCell(cell: cell, row: row, column: column) return cell } fileprivate func configureCell(cell: NSTableCellView, row: Int, column: Int){ let registration = fetchedResultsController.fetchedObjects! [row] switch column { case 0: cell.textField?.stringValue = registration.lastName ?? "" case 1: cell.textField?.stringValue = registration.firstName ?? "" case 2: cell.textField?.stringValue = registration.middleName ?? "" default: break } } } extension RegistrationReportsViewController : NSFetchedResultsControllerDelegate{ func controller(_ controller: NSFetchedResultsController, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?){ switch type { case .insert: if let newIndexPath = newIndexPath { tableView.insertRows(at: [newIndexPath.item], withAnimation: .effectFade) } case .delete: if let indexPath = indexPath { tableView.removeRows(at: [indexPath.item], withAnimation: .effectFade) } case .update: if let indexPath = indexPath { let row = indexPath.item for column in 0.. if let cell = tableView.view(atColumn: column, row: row, makeIfNecessary: true) as? NSTableCellView { configureCell(cell: cell, row: row, column: column) } } } case .move: if let indexPath = indexPath, let newIndexPath = newIndexPath { tableView.removeRows(at: [indexPath.item], withAnimation: .effectFade) tableView.insertRows(at: [newIndexPath.item], withAnimation: .effectFade) } @unknown default: fatalError() } } func controllerWillChangeContent(_ controller: NSFetchedResultsController) { tableView.beginUpdates() } func controllerDidChangeContent(_ controller: NSFetchedResultsController) { tableView.endUpdates() } }
0
0
1k
Jan ’20