Coredata propertiesToFetch - how does it work? [duplicate] - ios

This question already has answers here:
Swift 3. NSFetchRequest propertiesToFetch
(2 answers)
Closed 4 years ago.
I just need to fetch values of a single attribute from an entity and do not need to fetch all the attributes unnecessarily. To achieve this I have tried using 'propertiesToFetch' property with my fetch request, but it seems to return all the attribute values for the entity.
Say, I have an entity named 'Person' which has attributes 'name', 'age', 'height', 'weight'. Now I need to get only the height values. My fetch request is as below
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
request.propertiesToFetch = ["height"]
Now when I retrieve the values, I expect name, age, weight for each person be nil, and all persons have only height values.
But it's not that way, and I can still see the values for name, age, the weight which seems to me that all the properties are trying to be fetched which I want to avoid.
The above is just an example. As I am dealing with enormous data, I am trying to optimize the fetch time by picking up only the necessary values wherever possible.
Can someone please point out what I am missing here to make it proper?

I you have a large amount of data in you Entity and you don't want to load it into memory every time the object is faulted the solution is to use relationships. Generally the large amount of data is a single property (imageData, or something similar), and can be changed to a one-to-one relationship with an entity with a single property. This will allow you to assess the data just as easily (i.e. myObject.dataHolder.data instead of myObject.data), but you can't search or sort by it. You can do the same things for all properties that you don't need to search or sort by, but unless those properties are very large I don't see a big return on that.
As pointed out in the comments, propertiesToFetch is only for dictionaryResultType and is generally not a good solution for most applications where a managedObject subclass is needed.

Related

NSFetchRequest based on array property size

I have a NSManagedObject which has a (transformable) NSArray property arrayProperty.
I would like to execute a fetch request filtering for objects whose property size is less than 5. I tried
[NSPredicate predicateWithFormat:#"arrayProperty.#count <= 5"]
and
[NSPredicate predicateWithFormat:#"arrayProperty[SIZE] <= 5"]
but none of them work (giving Unsupported function expression count and Unsupported function [SIZE]).
Is there a way to achieve this?
This kind of thing isn't possible with transformable properties. Transformable are convenient for storing data, but once they're stored, that's all they are-- a bunch of bytes with no information about the data structure that created them. SQLite doesn't know that it's an array, so it's not able to do things like count how many items are in the array.
If you use transformable properties, you lose any ability to filter based on them, except for extremely basic tests like whether the value is nil.
If you need to do this kind of filtering, you'll need to consider how to change your data model. One possibility would be that instead of saving an array, create a new entity with a to-many relationship to store the values.

Fastest way to find an entity in CoreData

I have 20k unique labels that each have their own Entity with their own title.
What is the quickest way to get access to an Entity, given its title?
I know this can be done using a predicate, like so
fetch.predicate = NSPredicate(format: "title contains %#", "example title")
My issue with this approach is that it involves searching through every single one of the 20k Entities until the right one is found.
Is there a way to do this where all the titles are somehow indexed, and I can instantly get access to any label? Similar to how you can instantly get access to an item in an associative array, with array['item_name'].
Thanks.
Using a predicate is how you do it with Core Data.
Before you do anything, is this actually a problem? You don't mention that you've seen any performance issues. Are you having any, or is this still a theoretical problem?
You might improve performance by making sure that the "Indexed" box is checked for this attribute in the Core Data model editor. You might also consider adding a field to your entity that would contain a numeric hash of the title, and fetching based on the hash. You'd still be searching every entity but you'd be doing numeric comparisons instead of strings. You wouldn't be able to do substring searches (as your use of contains implies) but you would be doing the same thing as an associative array (which is also called a hash, for exactly this reason).
If none of that works well enough and you're searching strings very frequently, you'll need to investigate a different data model more suited to your needs-- like building a trie structure for fast searching.

Realm: Query for objects with same property

Is it possible in realm to query for objects that have the same property value?
Imagine a list of contacts with firstname and lastname. I want to query all contacts that have the same name and may be duplicates in the db.
As far as I'm aware, there's no automatic way to do that with NSPredicate (Of which Realm implements); it would need to be done manually.
That being said, it should be relatively trivial to do manually; simply loop through each object, performing a query that searches for that object's name properties, and see if the number of results returned is greater than 1.
That being said, depending on how big your data set is, this could become a very slow operation very quickly. Ideally, you might be better off ensuring that duplicate entries don't occur, or if they do, to somehow index them so they're easier to look up.

Need Help Understanding Transient Property in IOS Core Data

I don't understand why things have to be so difficult in core data. I have an entity that has 2 decimal attributes, "extended" and "qty"
All I want to do is extend these 2 values (multiply) and refer to this calculated value in a fetch. such as NSDecimalNumber * extendedPrice = [self.qty decimalNumberByMultiplyingBy:self.rate];
But in other cases I will want to #sum: this extended value attribute.
The web-available documentation and examples is very weak on how to do this which to me seems a very common thing to do.
Am I on the wrong track thinking I need a transient attribute and an awakefromfetch call? I get a crash when I try and refer to a transient attribute in a fetch.
You can't use transient attributes in fetch requests if you're using an SQLite store. This is because the fetch predicate is converted into an SQL query and no code is actually called. If the attribute doesn't exist in the store then it can't be used.
If you wanted to fetch the objects and then filter / sum them then that will work with a transient because at that point inTime you actually have the instances of the objects.

Creating sections with NSFetchedResultsController, on the fly

I'm using NSFetchedResultsController (NSFRC) to display information in a UITableView. I'm trying to create the option for the user to sort the cells in sections as opposed to alphabetically. The problem is, the sections would then be determined using downloaded information. On top of this the section for each item will be changing relatively often so I don't want to save the section. I have noticed the mention of transient attributes, in my research of similar problems, but i've never used these before I'm not sure if I can use them baring in mind that all the calculations are done once the data has already been loaded, and I also want this solution to be compatible with my previous Core Data database. Also I'm not particularly great at Core Data, (nor Objective-C at that!) so I'm not entirely sure how I'd go about doing this.
So here's what I want to go for if we're using transient attributes (this next bit is theoretical as I don't know if transient attributes are the correct way forward). I would like 4 possible sections, 0-3 (I'll rename them using the TableView delegate to get around sorting problems). When the calculations are done, each cell will be assigned the transient attribute (if needed, the default section would be 2). I hope this all makes sense.
Right, now for some theoretical code. First I create the transient property in the Data Model screen-thing, and make it transient by checking the transient check box... Sounds simple enough.
In the code for the calculations in willDisplayCell (needs to be done in wDC for a couple of reasons), the entity could be saved like this:
MyEntity *myEntity = [self.fetchedResultsController objectAtIndexPath:indexPath];
myEntity.sectionTransientProperty = 2;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Error: %#", error);
FATAL_CORE_DATA_ERROR(error);
return;
}
Done, right? Is that how we assign a value to a transient property?
Then I change the sorting option in NSFRC when I alloc it:
fetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:#"sectionTransientProperty"
cacheName:#"MyEntity"];
How are we doing, what else do I need to do? Or have I got this so horribly wrong I should just give up on Core Data and NSFRC? If you guys could help guide me through this I'd really appreciate it. If you need me to post any more code I would be happy to.
Regards,
Mike
If you want an FRC with sections, you have to add a sort descriptor to the fetch request, and that sort descriptor cannot be based on transient attributes.
See the documentation of initWithFetchRequest:managedObjectContext:sectionNameKeyPath:cacheName:`:
If the controller generates sections, the first sort descriptor in
the array is used to group the objects into sections; its key must
either be the same as sectionNameKeyPath or the relative ordering
using its key must match that using sectionNameKeyPath.
and Fetch Predicates and Sort Descriptors in the "Core Data Programming Guide":
The SQL store, on the other hand, compiles the predicate and sort
descriptors to SQL and evaluates the result in the database itself.
This is done primarily for performance, but it means that evaluation
happens in a non-Cocoa environment, and so sort descriptors (or
predicates) that rely on Cocoa cannot work. The supported sort
selectors are ...
In addition you cannot sort on transient properties using the SQLite store.
This means that you cannot create sections purely on transient attributes. You need a persistent attribute that creates the ordering for the sections.
UPDATE: A typical use of a transient attribute as sectionNameKeyPath is: Your objects have a "timeStamp" attribute, and you want to group the objects into sections with one section per month (see the DateSectionTitles sample code from the iOS Developer Library). In this case you have
a persistent attribute "timeStamp",
use "timeStamp" as first sort descriptor for the fetch request,
a transient attribute "sectionIdentifier" which is used as sectionNameKeyPath. "sectionIdentifier" is calculated from "timeStamp" and returns a string representing the year and the month of the timestamp, e.g. "2013-01".
The first thing the FRC does is to sort all fetched objects according to the "timeStamp" attribute. Then the objects are grouped into sections according to the "sectionIdentifier" attribute.
So for a FRC to group the objects into sections you really need a persistent attribute. The easiest solution would be to add a persistent attribute "sectionNumber" to your entity, and use that for "sectionNameKeyPath" and for the first sort descriptor.

Resources