NSFetchedResultsController add Objects manually - cocoa-touch

I recently stumbled across a difficult problem..
I'm normally using a NSFetchedResultsController to get Data out of my CoreData, and display it within a TableViewController.
The problem I have now is that I can't get the results I want with a NSFetchRequest right away, because having a m:n relationship and I implemented a Table in Core Data (References) which stores the references to the Objects...
So what I do now is, I use a fetch Request:
NSArray* references = [self.context executeFetchRequest:fetchRequest error:&error];
and then iterate through this array to get my Objects:
for(References* ref in references)
{
Post* tmp = ref.ref_of_post;
}
So is there a way to manually add these objects to my NSFetchedResultsController or is there a possibility to get the wanted object trough a NSFetchRequest?
Thanks for your help.

Never mind that.
I just added these Objects to a NSMutableArray and then would use this Array in the same way as the NSFetchedResultsController..

Related

Retrieve Specific Object from Core Data

I'm new to Core Data and wondering if it is possible to get an object based on it's attributes, more specifically, an uniqueID I assigned to it. I'm trying to do this because I'm interfacing with a web server, which provides data that will updated the Core Data. I want to search through each of the web server objects, check the timestamp, and if it's different, retrieve that object from core data, and update. I've looked at using existingObjectWithId but it seems like I would have to know which object I'm searching for, or the ID of that object. I've also thought about sorting the data in both arrays, and then checking each simultaneously, but didn't think that is viable.
Here is what I'm doing so far:
-(NSMutableArray*) updateRootBeers:(NSMutableArray*)webRootBeerList{
NSManagedObjectContext* moc = [self managedObjectContext];
NSFetchRequest* fetchRequest = [[NSFetchRequest alloc]initWithEntityName:#"Rootbeer"];
coreDataRootBeerList = [[moc executeFetchRequest:fetchRequest error:nil]mutableCopy];
//check to see if core data has data, if not, call function to populate the list
if (coreDataRootBeerList.count <=0) {
[self addRootBeerToCoreData:webRootBeerList];
}else{
//otherwise I want to update the core data object if object data is different.
for(RootBeer* currentRootBeer in webRootBeerList){
RootBeer* mRootBeer = [moc existingObjectWithId:currentRootBeer error:nil];
}
}
}
I've also thought about using nested for loops to check for the data in each array, but that seems like poor coding.
Any help or thoughts would be great.
You want to make an NSFetchRequest. You can set the entity and provide a Predicate. Really simple and clean.

Check if a specific data is into core data

Here's the question. I have a table where I save some data, which I get from a NSArray of NSDictionaries which will have the properties to be saved. Each dictionary in the array is a separated entity, so I loop the dictionary and save it using insertNewObjectForEntityForName to create diferent entity.
I need to refesh the data, but when is saving the data is duplicating the data that exist already in coredata. Im trying to check if the id exist on the core data using
for(NSDictionary *exist in dic){
if([[campaignDictionary objectForKey:#"element"] isEqualToString:#"id"]){
idToCheck = [dic objectForKey:#"value"];
}
}
if(table.campaign_id == idToCheck){
return exist = YES;
}
but its leaving the rest of the data without being checked, so only the id not being duplicated, any ideas to how approach this? thanks!
I decided it was best to delete all my content from Coredata before inserting the new content, thanks!!

How to access CoreData entities based on a to-many relationship of another entity?

I am learning CoreData with a sample inventory app. My Data Model has 2 entities, "Possession" and "Asset Type". Possessions have a to-one relationship to Asset Types called "assetType" and Asset Types have a to-many relationship to Possessions named "possessions". Each Possession has only one Asset Type, but Asset Types have many Possessions.
I'd like to sort a tableview into sections based on asset types. I need some help populating my data structure for this though.
Here is how I'll model my table view controller
NSArray for table sections
each section object in the array will be an NSDictionary with 2 keys, #"Header" - which will be the Asset Type, and #"Possessions" which is an array of possessions of that asset type.
I can handle building my table view from this structure no problem. I can also handle fetching the Asset Types from CoreData into the header key of my dictionary. Where I am stumped is how do I take advantage of the to-many relationship that asset types have to possessions so I can get the possessions into an array for the dictionary.
How do I get each Asset Type's possessions into an array?
Do I need to make a fetch request with a predicate to fetch possessions that have the matching asset type, or is there a simpler way? - Seems that would be inefficient as it would have to check all possessions for a match!?!?!?!?
Is the to-many relationship "possessions" of AssetType entity an accessible property of the AssetType entity? If so how do I access it? What does it return?
I am not looking for free code, but I am willing to post mine if needed. What I'd really like is to know the best way to solve this problem and maybe pointed to helpful info online to accomplish this. I am not a complete newb, but I am still having trouble wrapping my head around CoreData and thus far the Apple docs are still pretty confusing to me on this subject. I am appreciative for any help offered.
If you've created your AssetType class with Xcode default NSManagedObject template (see image)
you should have something like that in your AssetType.h:
#interface AssetType : NSManagedObject
#property (nonatomic, retain) NSSet *possessions;
#end
#interface AssetType (CoreDataGeneratedAccessors)
- (void) addPossessionsObject: (Possession *) value;
- (void) removePossessionsObject: (Possession *) value;
- (void) addPossessions: (NSSet *) value;
- (void) removePossessions: (NSSet *) value
#end
So if you have an AssetType object, you can access all Possession objects related to it via the possessions property. It is not ordered by default though, so to access these objects as an array, you will need to call the -allObjects method of the set which returns the objects within the set as an array and then probably sort these objects somehow.
Edit:
Also, even if you did not create the NSManagedObject subclass that way and it does not have the possessions property implemented yet, you could add this property to the class in the just same way as stated in the example above and implement it within the AssetType.m as #dynamic possessions.
from what I'm reading I suspect this is much easier than you might think.
It sounds to me like you have envisaged using a dictionary data structure with for use in your UITableController's tableView:cellForRowAtIndexPath: method, when you probably don't need to use one at all.
When you Table view controller instantiates, (viewDidLoad: is probably the most appropriate place) simply retrieve your assets with code like this:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Asset" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
// handle errors here
}
[fetchRequest release];
If necessary assign the fetchedObjects array to an instance variable of type NSArray so you can refer to it in multiple places in the UITableViewController class managing the table. Then after the above code you can do something like this:
self.assets = fetchedObjects;
If you have not created a custom subclass for your asset NSManagedObject, then each object in the array will be of type NSManagedObject and you will need to read it into a variable of that type.
When you need to the list of possessions related to an asset, it's already there in each asset object in your array (that's the beauty of CoreData, if it's not actually instantiated in memory, the moment you try to access the property, CoreData will automagically instantiate it for you).
So let's say you have not defined a custom class for your NSManagedObject then your array objects will be of that type. Assign one of the asset objects in your array to a local variable named (appropriately) asset,
For example, this will assign the object at index 0 to a local variable.
NSManagedObject *asset = [self.assets objectAtIndex:0];
You get can get your set of possessions with the code:
NSSet *assetPossessions = [asset valueForKey:"#possessions"];
(presuming the relationship defined in the model editor in xCode has been named "possessions")
Alternatively If you generated your own custom subclass for the Asset NSManagedObject, then, this might be a better example:
MyManagedAssetObject *asset = [self.assets objectAtIndex:0];
NSSet *assetPossessions = asset.possessions;
Note in this example, I have presumed you are not using a NSFetchedResultsController. It is actually even easier to manage a table using one, however as is often the case with programming it is easier only once you know that "just one more thing" and so (paradoxically) complicates the answer. Since you didn't mention it, I have assumed you are not using it.
Hope this helps. Paul

Detecting duplicate entries in core data and removing them

I have started to work on a core data project. The data to store in the database comes from the server and I am able to store it successfully into coredata. However, each fetch is resulting in duplicate entries. What is the best way to check whether the data exists in core data and append only if the data is not found.
Here is my implementation so far:
for (NSDictionary *dict in array) {
DatabaseManagement *mo = [NSEntityDescription insertNewObjectForEntityForName:#"Subscription" inManagedObjectContext:context];
[mo setValuesForKeysWithDictionary:dict];
The array contains nested dictionary with keys corresponding to my entities attribute names.
I know I can use NSPredicate to achieve this but can someone provide sample code or some resources?

traverse Core Data object graph with added predicate?

I want to load a client object and then pull their related purchase orders based on whether they have been placed or not, purchase orders have an IsPlaced BOOL property.
So I have my client object and I can get all purchase orders like this, which is working great:
purchaseordersList =[[myclient.purchaseorders allObjects] mutableCopy];
But ideally I would actually like 2 array's - one for each order type: IsPlaced=YES and IsPlaced=NO
How do I do that here? Or do I need to do another fetch?
First, there is no reason to be turning the set into an array unless you are sorting it and there is no reason to be turning that array into a mutable array. Did you get that from some example code?
Second, you can filter an array or a set by using a predicate so you can create two sets (or arrays) easily via:
NSSet *placed = [[myclient purchaseorders] filteredSetUsingPredicate:[NSPredicate predicateWithFormat:#"isPlaced == YES"]];
NSSet *notPlaced = [[myclient purchaseorders] filteredSetUsingPredicate:[NSPredicate predicateWithFormat:#"isPlaced == YES"]];
If you are wanting to use this for a UITableView then look into a NSFetchedResultsController instead. It will save you a LOT of boiler-plate code.
Do you remember what example code you got that from? Been seeing that -mutableCopy a lot lately and would love to quash it. :)