I am currently building a story feature in my iOS app. Like on Instagram and Snapchat. The story also has a circle around the image. It changes the color if the story has been seen.
At the start of the App, I save some values in CoreData to identify every story.
var context: NSManagedObjectContext!
var storys = [Story]()
private init() {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
context = appDelegate.persistentContainer.viewContext
fetchStoryItems()
}
func addStorys(with shoeID: String, raffles: String, seenStory: Bool) {
let storyItem = NSEntityDescription.insertNewObject(forEntityName: "Story", into: context) as! Story
storyItem.shoeID = shoeID
storyItem.newRaffles = raffles
storyItem.seen = seenStory
if !storys.contains(where: {$0.shoeID == shoeID}) {
storys.append(storyItem)
saveContext()
}
}
func fetchStoryItems() {
let request: NSFetchRequest<Story> = NSFetchRequest<Story>(entityName: "Story")
do {
let storyItemsArray = try context.fetch(request)
storys = storyItemsArray
} catch {
print(error.localizedDescription)
}
}
func saveContext() {
do {
try context.save()
} catch {
print(error.localizedDescription)
}
}
This works fine and every value is stored once in CoreData. So that the circle is displayed in the correct color, I change the value if the story has been seen. If the user taps von a story the following methods are executed.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
CoreDataStoryCheck.sharedInstance.storyTapped(with: Array(storyShoeModel.values)[indexPath.row].ID!, seenStory: true)
collectionViewOrTableView = 1
performSegue(withIdentifier: "details", sender: indexPath.row)
}
func storyTapped(with shoeID: String, seenStory: Bool) {
if let story = storys.first(where: {$0.shoeID == shoeID && $0.seen == false}) {
story.setValue(true, forKey: "seen")
saveContext()
}
}
Now here comes my issue: Every time I am calling this method my data duplicates in CoreData. I have found that this happens every time when I call saveContext(). I don't understand why this happens.
Related
I want to track completed Topics list in TableView
I have set delegate which confirms to tableView topic mark as completed
protocol TopicDetialVCDelegate: class {
func hasBeenCompletedTopic()
}
TableViewVC
func hasBeenCompletedTopic() {
isPerformedDelegate = true
if !completedTopicIdArray.contains(completedTopicId) {
completedTopicIdArray.append(completedTopicId)
}
print("completed Topics \(completedTopicIdArray)")
print("TopicVC: Completed Topics total: \(completedTopicIdArray.count)")
}
This is working, but i want to persist always mark as completed which already marked
Here is code of CellForRowAt
if isPerformedDelegate {
for _ in 0...completedTopicIdArray.count {
if completedTopicIdArray.contains(filteredTopicArray[indexPath.row].id!) {
cell.topicCompletedTickImageView.image = #imageLiteral(resourceName: "Tick")
}
}
}
What i want
There should be a array which get all completed topics idz, and on every run of app checks if cell indexpath contain topicID show Tick image
I can use UserDefaults like this
UserDefaults.standard.set(array, forkey: "abc")
but problem is array will reinitialize on run of app again
like so in ViewWillDisappear
override func viewWillDisappear(_ animated: Bool) {
UserDefaults.standard.set(completedTopicIdArray, forKey: "completedTopics")
UserDefaults.standard.synchronize()
}
accessing in ViewDidLoad
let topics = UserDefaults.standard.array(forKey: "completedTopics")
print(topics as? [Int] ?? [Int]())
I have been solved this Problem Using CoreData, want to share
Declare empty array
var completedTopicsIdPersistArray: [Int] = [Int]()
CoreData Method for Creating
func persistIdIntoCoreData() {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedObjectContext = appDelegate.persistentContainer.viewContext
guard let entity = NSEntityDescription.entity(forEntityName: "ComTopicDB", in: managedObjectContext)
else {
print("Entity Not Found")
return
}
let topicIdz = NSManagedObject(entity: entity, insertInto: managedObjectContext)
topicIdz.setValue(completedTopicId, forKey: "topicId")
do {
try managedObjectContext.save()
}
catch let error as NSError {
print("Unable to save into CoreData: \(error.userInfo)")
}
}
CoreData Method for Retrieving
func retrieveIdFromCoreData() {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedObjectContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "ComTopicDB")
do {
let topicIdz = try managedObjectContext.fetch(fetchRequest)
for id in topicIdz {
let unwrapId = id.value(forKey: "topicId") as! Int
if !completedTopicsIdPersistArray.contains(unwrapId) {
completedTopicsIdPersistArray.append(unwrapId)
}
}
}
catch let error as NSError {
print("Found issue during retrieve id from CoreData:\(error.userInfo)")
}
}
Calling inside of delegate method, which confirms topic completed
func hasBeenCompletedTopic() {
isPerformedDelegate = true
if !completedTopicIdArray.contains(completedTopicId) {
completedTopicIdArray.append(completedTopicId)
persistIdIntoCoreData()
}
print("completed Topics \(completedTopicIdArray)")
print("TopicVC: Completed Topics total: \(completedTopicIdArray.count)")
retrieveIdFromCoreData()
}
and finally CellForRowAt Method
if completedTopicsIdPersistArray.contains(filteredTopicArray[indexPath.row].id!) {
cell.topicCompletedTickImageView.image = #imageLiteral(resourceName: "Tick")
}
Finally call inside ViewWillAppear, because it comes from topicDetailVC back
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
retrieveIdFromCoreData()
}
Now all topics will show Tick icon, which marked as completed, even terminate and relaunch app
The problem: I cannot get data downloaded into arrays in a singleton class to populate table views in two view controllers.
I am writing a bank book iOS app with a Parse backend. I have a login viewController and four other view controllers in a Tab Bar Controller. I have a singleton class that gets data from the Parse server and loads four arrays. I want that data to populate table views in two other view controllers. I want to make as few data calls as possible. The initial view controller is where user enters debits and credits. So my plan was to call GetData class from the viewDidLoad to populate tables in case user visits them without entering a debit or a credit.
When a debit or credit is entered, there is one function where after the debit or credit is saved to Parse server, the GetData class is called again to update the arrays in the GetData class.
The two view controllers access the arrays in the GetData class to fill the tables, and there is a tableView.reloadData() call in the viewDidAppear in each view controller when the view is accessed via the tab controller.
It works intermittently at best. sometimes I get five successful updates and then it keeps displaying old data, then it will suddenly display all the data.
Looking at my cloud DB, all the entries are there when made, and I have verified the viewWillAppear is firing in each view controller who accessed.
What I need is a reliable method to get the data to update in the other view controllers every. time. I will gladly scrap this app and rewrite if needed.
Here is the code of my singleton class:
class GetData {
static let sharedInstance = GetData()
var transactionArray = [String]()
var dateArray = [String]()
var toFromArray = [String]()
var isDebitArray = [String]()
func getdata() {
let query = PFQuery(className:"Transaction")
query.findObjectsInBackground { (objects, error) in
self.transactionArray.removeAll()
self.dateArray.removeAll()
self.toFromArray.removeAll()
self.isDebitArray.removeAll()
print("query fired")
if objects != nil {
for object in objects! {
if let amount = object.object(forKey: "amount") as? String {
if let date = object.object(forKey: "date") as? String {
if let toFrom = object.object(forKey: "toFrom") as? String {
if let isDebit = object.object(forKey: "isDebit") as? String {
self.transactionArray.append(amount)
self.dateArray.append(date)
self.toFromArray.append(toFrom)
self.isDebitArray.append(isDebit)
}
}
}
}
}
}
self.transactionArray.reverse()
self.dateArray.reverse()
self.toFromArray.reverse()
self.isDebitArray.reverse()
dump(self.toFromArray)
}
}
}
Here is a sample of one of the view controllers:
class RecordVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var recordTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
recordTableView.delegate = self
recordTableView.dataSource = self
recordTableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
recordTableView.reloadData()
print("recordVC viewWillAppear fired")
}
#IBAction func resetFoundButton(_ sender: Any) {
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = recordTableView.dequeueReusableCell(withIdentifier: "RecordCell", for: indexPath) as! RecordCell
cell.amountLabel?.text = "$\(GetData.sharedInstance.transactionArray[indexPath.row])"
cell.dateLabel?.text = "\(GetData.sharedInstance.dateArray[indexPath.row])"
cell.toFromLabel?.text = "\(GetData.sharedInstance.toFromArray[indexPath.row])"
let cellColor = backGroundColor(isDebit: GetData.sharedInstance.isDebitArray[indexPath.row])
cell.backgroundColor = cellColor
cell.backgroundColor = cellColor
return cell
}
func backGroundColor(isDebit:String) -> UIColor{
if isDebit == "false" {
return UIColor.green
} else {
return UIColor.blue
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return GetData.sharedInstance.transactionArray.count
}
}
Thank you
I would say that instead of reloading the tables by calling tableView.reloadData() in viewWillAppear() , after your query execution and data updates in GetData Class , then you should fire a notification or use a delegate to reloadData() in tableview.
Whats happening is that sometimes when the tableView.reloadData() gets called the Data in the singleton class (GetData class) has not yet updated.
func getdata() {
let query = PFQuery(className:"Transaction")
query.findObjectsInBackground { (objects, error) in
self.transactionArray.removeAll()
self.dateArray.removeAll()
self.toFromArray.removeAll()
self.isDebitArray.removeAll()
print("query fired")
if objects != nil {
for object in objects! {
if let amount = object.object(forKey: "amount") as? String {
if let date = object.object(forKey: "date") as? String {
if let toFrom = object.object(forKey: "toFrom") as? String {
if let isDebit = object.object(forKey: "isDebit") as? String {
self.transactionArray.append(amount)
self.dateArray.append(date)
self.toFromArray.append(toFrom)
self.isDebitArray.append(isDebit)
// Here you should fire up a notification to let the 2 ViewControllers know that data has to be reloaded.
}
}
}
}
}
}
self.transactionArray.reverse()
self.dateArray.reverse()
self.toFromArray.reverse()
self.isDebitArray.reverse()
dump(self.toFromArray)
}
}
For each UITextView using UserDefaults, I've made a function to save and a function to display.
Whatever text is added needs to be displayed at the time of adding, saved and then displayed again when opening the app again.
If I install the app with ONLY the function to save, quit the app and add the function to display then reinstall without deleting the installed app everything works perfectly.
If I install the app with both functions added it doesn't work.
There has to be a simple solution for this, I'm obviously doing something wrong.
The data from one textView is used to calculate results and then to display them on the other textView.
All data is added with other functions, none by the user.
numberHistoryView.isEditable = false
numberHistoryView.isSelectable = false
func saveHistoryTextView()
{
let defaults = UserDefaults.standard
let numberHistory = numberHistoryView.text
defaults.set(numberHistory, forKey: "combos")
}
func displaySavedHistory()
{
let defaults = UserDefaults.standard
let savedCombos = defaults.object(forKey: "combos") as? String ?? ""
numberHistoryView.text = savedCombos
}
func saveFrequencyTextView()
{
let defaults = UserDefaults.standard
let numberFrequency = numberFrequencyCount.text
defaults.set(numberFrequency, forKey: "frequency")
}
func displaySavedFrequency()
{
let defaults = UserDefaults.standard
let savedFrequency = defaults.object(forKey: "frequency") as? String ?? ""
numberFrequencyCount.text = savedFrequency
}
override func viewWillDisappear(_ animated: Bool)
{
saveHistoryTextView()
saveFrequencyTextView()
}
override func viewWillAppear(_ animated: Bool)
{
displaySavedHistory()
displaySavedFrequency()
}
This depends on the order and timing in which you are calling save and display methods.
When you're installing a fresh app, there will be no data in saved in UserDefaults. So when you call displaySavedHistory() and displaySavedFrequency() methods in viewWillAppear(_:), nothing will be fetched because nothing is saved yet.
Now, when you save the data using saveHistoryTextView() and saveFrequencyTextView() methods in viewWillDisappear(_:) and then you kill and run the app again, the saved data will be fetched and displayed.
Also, since you're saving the data in UserDefaults, and UserDefaults are saved within the sandbox, so the data won't persist when you delete the app. You've to save the data in iCloud or keychain etc. if you want to persist the data even after app deletion.
Once I put my brain into a theta state with the right frequency I managed to figure it out.
Thanks to #Naresh and all other contributors for trying to help as you may have assisted me a little.
The solution basically just required a simple if statement.
Everything now works perfectly.
func saveHistoryTextView()
{
if numberHistoryView.text?.count != nil
{
let defaults = UserDefaults.standard
defaults.set(numberHistoryView.text!, forKey: "combos")
}
}
func displaySavedHistory()
{
let defaults = UserDefaults.standard
if let savedCombos = defaults.string(forKey: "combos")
{
numberHistoryView.text = savedCombos
}
}
func saveFrequencyTextView()
{
if numberFrequencyCount.text?.count != nil
{
let defaults = UserDefaults.standard
defaults.set(numberFrequencyCount.text!, forKey: "frequency")
}
}
func displaySavedFrequency()
{
let defaults = UserDefaults.standard
if let savedFrequency = defaults.string(forKey: "frequency")
{
numberFrequencyCount.text = savedFrequency
}
}
}
override func viewWillDisappear(_ animated: Bool)
{
saveHistoryTextView()
saveFrequencyTextView()
}
override func viewWillAppear(_ animated: Bool)
{
displaySavedHistory()
displaySavedFrequency()
}
You can do it with property observer as:
private let DATA_KEY = "Saved Data"
//After initialising the outlet we can set the data
#IBOutlet weak var textView: UITextView! {
didSet {
textView.text = self.data
}
}
private var data: String {
set {
//Save data in user defaults
UserDefaults.standard.set("The value you will assign", forKey: DATA_KEY)
}
get {
//get the data from user defaults.
return UserDefaults.standard.value(forKey: DATA_KEY) as? String ?? ""
}
}
//UITextViewDelegate: set the text data on end of UITextView editing
func textViewDidEndEditing(_ textView: UITextView) {
self.data = textView.text
}
I'm moving this getCloudKit function from ViewController.swift to Lay.swift so I can keep everything in a single class.
var objects = [Lay]()
override func viewDidLoad() {
super.viewDidLoad()
self.refreshControl?.addTarget(self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged)
self.getCloudKit()
}
func handleRefresh(refreshControl: UIRefreshControl) {
self.objects.removeAll()
self.getCloudKit()
}
func getCloudKit() {
let now = NSDate()
let predicate = NSPredicate(format: "TimeDate > %#", now)
let sort = NSSortDescriptor(key: "TimeDate", ascending: true)
let container = CKContainer.defaultContainer()
let publicData = container.publicCloudDatabase
let query = CKQuery(recordType: “lay”, predicate: predicate)
query.sortDescriptors = [sort]
publicData.performQuery(query, inZoneWithID: nil) { results, error in
if error == nil {
for lay in results! {
let newlay = Lay()
newLay.tColor = lay["tColor"] as! String
newLay.timeDate = lay["TimeDate"] as! AnyObject
newLay.matchup = lay["Matchup"] as! String
let applicationDict = ["tColor" : newLay.tColor, "Matchup" : newLay.matchup]
let transfer = WCSession.defaultSession().transferUserInfo(applicationDict)
self.objects.append(newLay)
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.refreshControl!.endRefreshing()
self.tableView.reloadData()
})
} else {
print(error)
}
}
}
The problem is when I move it (and the necessary related code):
Error in Lay.swift on TableViewController().refreshControl!.endRefreshing()
saying "fatal error: unexpectedly found nil while unwrapping an
Optional value"
Need to put my WCSession: transferUserInfo code from getCloudKit in my AppDelegate.swift, but keep getting errors when I try
New ViewController.swift:
override func viewDidLoad() {
super.viewDidLoad()
self.refreshControl?.addTarget(self, action: "handleRefresh:", forControlEvents: UIControlEvents.ValueChanged)
Lay().getCloudKit()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return Lay().objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
let object = Lay().objects[indexPath.row];
if let label = cell.textLabel{
label.text = object.matchup
}
return cell
}
func handleRefresh(refreshControl: UIRefreshControl) {
Lay().objects.removeAll()
Lay().getCloudKit()
}
New Lay.swift:
var objects = [Lay]()
func getCloudKit() {
let now = NSDate()
let predicate = NSPredicate(format: "TimeDate > %#", now)
let sort = NSSortDescriptor(key: "TimeDate", ascending: true)
let container = CKContainer.defaultContainer()
let publicData = container.publicCloudDatabase
let query = CKQuery(recordType: “lay”, predicate: predicate)
query.sortDescriptors = [sort]
publicData.performQuery(query, inZoneWithID: nil) { results, error in
if error == nil {
for lay in results! {
let newlay = Lay()
newLay.tColor = lay["tColor"] as! String
newLay.timeDate = lay["TimeDate"] as! AnyObject
newLay.matchup = lay["Matchup"] as! String
let applicationDict = ["tColor" : newlay.tColor, "Matchup" : newlay.matchup]
let transfer = WCSession.defaultSession().transferUserInfo(applicationDict)
self.objects.append(newlay)
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
TableViewController().refreshControl!.endRefreshing()
TableViewController().tableView.reloadData()
})
} else {
print(error)
}
}
New AppDelegate:
private func setupWatchConnectivity() {
if WCSession.isSupported() {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
}
}
private func sendUpdatedDataToWatch(notification: NSNotification) {
if WCSession.isSupported() {
let session = WCSession.defaultSession()
if session.watchAppInstalled
{
let applicationDict = ["TColor" : Lay().tColor, "Matchup" : Lay().matchup]
let transfer = WCSession.defaultSession().transferUserInfo(applicationDict)
NSLog("Transfer AppDelegate: %#", transfer)
NSLog("Trans AppDelegate: %#", applicationDict)
session.transferCurrentComplicationUserInfo(applicationDict)
}
}
}
Your code has ViewController() and Lay() throughout. This will create new instances of those objects. Therefore, although refreshControl is non-nil in your actual view controller, it will be nil in a newly created one.
By splitting out the getCloudKit function, you're allowing the view controller to just manage the view, and the new class to just manage Cloud Kit. This is good, so ideally your Cloud Kit controller should not know anything about the view controller. Therefore, getCloudKit shouldn't be calling reloadData. Instead, you could pass a closure into getCloudKit that gets called when the query finishes. Something along the lines of:
func getCloudKit(completion completionHandler: (([Lay]) -> Void)?) {
...
publicData.performQuery(query, inZoneWithID: nil) { results, error in
if error == nil {
...
if let completion = completionHandler {
completion(self.objects)
}
} else {
print(error)
}
}
Then in ViewController:
let layCloudKit = LayCloudKit()
layCloudKit.getCloudKit(completion: { (objects) -> Void in
dispatch_async(dispatch_get_main_queue(), {
self.objects = objects
self.refreshControl!.endRefreshing()
self.tableView.reloadData()
})
})
Note that I've assumed you would put the Lay Cloud Kit controller into a separate Swift file, as the Lay model class shouldn't need to know about Cloud Kit. If you want to put it in the same file as Lay, then you should mark the func as static or class, because you don't want to create a dummy instance of Lay just to call getCloudKit. In that case, you would call it using Lay.getCloudKit (ie. specifying the Lay class, rather than a Lay instance).
I'm new to iOS development and was wanting to know which data type I should specify to store multiple strings (array). The app is to do with food and I need to store multiple ingredients as one attribute.
I was thinking of making ingredient as entity, but I just want to make it easy for a starter.
I have read about transformable type but people don't seem to recommend using it to store arrays.
Warning: opinionated answer ahead.
You don't.
Storing things in an array does not make anything easier for you. On the contrary, it will make things much harder just an hour in. Imagine you want to show all Recipes that contain a selected Ingredient. That wouldn't be easy with your array hack, with a proper model it's only a couple line of code.
I would recommend to use a good old relationship with a "Join-entity".
Yes, this is more complicated than hacking something together that barely works. But it's the correct way.
What you was thinking of is exactly what you should do. Core Data is made to store values in array like structure. You should create entity Ingredients and connect your Food entity (or whatever you would like to call it) with relationship with Ingredients entity.
there is a way. You can do each element manually e.g.
You have your array:
let employee: NSMutableArray = []
employee.addObject(["name":"Bill","LastName":"Hanks"])
employee.addObject(["name":"Rolex","LastName":"Swarzer"])
employee.addObject(["name":"Clive","LastName":"Martin"])
employee.addObject(["name":"Jimi","LastName":"Hendrix"])
Assuming you have created your coreData with Entity "Employee" and Attributes "name" and "lastname" you do the following to add it in...
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDel.managedObjectContext
for item in employee {
do {
let newUser = NSEntityDescription.insertNewObjectForEntityForName("Employee", inManagedObjectContext: context)
newUser.setValue(item["name"], forKey: "name")
newUser.setValue(item["LastName"], forKey: "lastname")
try context.save()
} catch {
//do nothing
}
You can then fetch all elements using your fetch request or the NSFetched Results Controller
I have done in Swift 4,
Storing more Arrays into allDataArray (One Array). Fetching array objects from CoreData (AllData) and Displaying in TableView
import UIKit
import Foundation
import CoreData
class ViewController: UIViewController {
var allTableDataArray : [AllData] = [AllData]()
let allDataArray : NSMutableArray = []
var listOfArray1 = ["#849578", "#849302"]
var listOfArray2 = ["Vasuki Shiv", "Prathap Dusi"]
override func viewDidLoad() {
super.viewDidLoad()
saveAllDataToCoredata()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
fetchAllDataFromCoredata()
}
func saveAllDataToCoredata() {
deleteAllData(entity: "AllData")
let context = PersistenceSerivce.context
allDataArray.add(["requestNo" : listOfArray1[0], "vendorName" : listOfArray2[0]])
allDataArray.add(["requestNo" : listOfArray1[1] , "vendorName" : listOfArray2[1]])
for item in (allDataArray){
do {
let newUser = NSEntityDescription.insertNewObject(forEntityName: "AllData", into: context)
guard let requestNoNew = item as? [String:Any] else {
return
}
let requestNoStr = requestNoNew["requestNo"] as! String
newUser.setValue(requestNoStr, forKey: "requestNo")
guard let vendorNameNew = item as? [String:Any] else {
return
}
let vendorNameStr = vendorNameNew["vendorName"] as! String
newUser.setValue(vendorNameStr, forKey: "vendorName")
PersistenceSerivce.saveContext()
try context.save()
} catch {
//do nothing
}
}
}
func fetchAllDataFromCoredata(){
let context = PersistenceSerivce.context
let fetchRequest = NSFetchRequest<AllData>(entityName: "AllData")
allTableDataArray.removeAll()
do {
allTableDataArray = try context.fetch(fetchRequest)
} catch {
print("Unable to fetch from Coredata", error)
}
}
func deleteAllData(entity: String) {
let managedContext = PersistenceSerivce.context
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try managedContext.fetch(fetchRequest)
for managedObject in results
{
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
managedContext.delete(managedObjectData)
}
} catch let error as NSError {
print("Delete all data in \(entity) error : \(error) \(error.userInfo)")
}
}
}
//MARK:- UITableView
extension ViewController : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView,
heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (allTableDataArray.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: “TableViewCellID”) as? TableViewCell
let allData = allTableDataArray[indexPath.row]
cell?.requestNoLabel.text = allData.requestNo
cell?.vendorNameLabel.text = allData.vendorName
return cell!
}
}