简体   繁体   中英

iOS - Reorder Items in CoreData

I have a tableView and an array locationsArray . The locations array is filled on viewDidLoad from data in my CoreData.

I have implemented the reorder methods on the tableView and that works fine however I can't figure out how to save the reordered array back into CoreData. I've tried deleting everything in CoreData and just saving the new reorderedArray. Although this is obviously very costly resource wise it seems to just load the elements back into the array in a seemingly random order.

Is there an easy way to do this that I am missing or can you not store things in CoreData in a certain order?

Strictly saying, it is impossible to store objects in certain order . You can only set the order for retrieved objects

When you retrieve locationsArray from CoreData, you have no any guaranties about their order. The only way - add field to your Managed Object that will be used to order your locations.

Than, on retrieval, you'll be able to use locationsArray = [locationsArray sortedArrayUsing<#WhateverYouNeed#>]; .

You can, also, achieve this by using sortDescriptors property of NSFetchRequest. It will provide you with desired behaviour from the box. The only downside of it, that your NSSortDescriptor in that case cannot be defined by block, so if you ordering is using some complex approach, you'll need to sort the result with already fetched data

use the predicate to sort the array or after fetching the array from coredata sort it using

 NSArray *sortedlocationarray = [filteredlocationarray sortedArrayUsingDescriptors:@[sortDescriptor]];

where filteredlocationarray is from coredata.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM