Edit: After reading please look at my comment to see where I'm at now :)*
So I have a UISegementedControl with newest,price,title, and item type and for some reason everytime I switch tabs the itemType label only keeps one of the labels for the item type.
Example: 3 Cells of itemType Electronics all with the same itemType label, then when you switch to another segment, only the newest Electronic cell itemType Label stays.
I have no idea why it's doing this after reviewing my code and researching.
Note: I am using CoreData
segmentChange
Function
@IBAction func segmentChange(_ sender: Any) {
//segment control function
attemptFetch()
tableView.reloadData()
}
attemptFetch
function:
func attemptFetch() {
// function needed to fetch and display items
let fetchRequest: NSFetchRequest<Item> = Item.fetchRequest()
//tells what item or entity you're tracking
let dateSort = NSSortDescriptor(key: "created", ascending: false)
let priceSort = NSSortDescriptor(key: "price", ascending: true)
let titleSort = NSSortDescriptor(key: "title", ascending: true)
let itemTypeSort = NSSortDescriptor(key: "type", ascending: true)
if segment.selectedSegmentIndex == 0 {
fetchRequest.sortDescriptors = [dateSort]
} else if segment.selectedSegmentIndex == 1 {
fetchRequest.sortDescriptors = [priceSort]
} else if segment.selectedSegmentIndex == 2 {
fetchRequest.sortDescriptors = [titleSort]
} else if segment.selectedSegmentIndex == 3 {
fetchRequest.sortDescriptors = [itemTypeSort]
}
let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
//instantiates NSFetchedResultsController
controller.delegate = self
//tells the functions what to do and listen
self.controller = controller
do {
// attempting fetch of item
try controller.performFetch()
} catch {
let error = error as NSError
print("\(error)")
}
}
My savePressed
function when you create a new item:
@IBAction func savePressed(_ sender: Any) {
//saves to disk/"database"
var item: Item!
let picture = Image(context: context)
picture.image = thumbImage.image
if itemToEdit == nil {
// if no objects then create new item
item = Item(context: context)
//insert entity into context
} else {
//takes existing cell and lets you edit it
item = itemToEdit
}
item.toImage = picture
// item entity to image entity
if let title = titleField.text {
item.title = title
}
if let price = priceField.text {
item.price = (price as NSString).doubleValue
// lets use properties of NSString and convert to double
}
if let details = detailsField.text {
item.details = details
}
item.toStore = stores[storePicker.selectedRow(inComponent: 0)]
item.toItemType = itemTypes[storePicker.selectedRow(inComponent: 1)]
// relationship from item to store or vise versa is picked (component is the # of columns)
ad.saveContext()
_ = navigationController?.popViewController(animated: true)
}