Save new object at index path Core Data - core-data

Every time I Save a new Object it appears on the top of my UITableView. What If want it to apper at a different index path or different section?
For Example is it Possible to insert the new Object at:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[[self objectsFetched] count]-1 inSection:0];
or
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[[self objectsFetched] count]-1 inSection:1];
I Can accomplish the above scenario with NSMutableArrays, but how do I achieve the same with Core Data?

With Core Data you have a big bag of contents, how you display that in a table view is entirely up to you. The process of achieving this is by sorting the big bag, generally as you extract the contents.
Look at NSFetchRequest and you will see it takes an array of sortDescriptors. You can make these sort descriptors look at any key in your managed objects. If you want, you can add an explicit order key and set the value, or a date stamp.
How you sort is up to you, but you do need to sort to specify the order you want.

Related

Initialize document data source by key attribute (instead of UNID)

We have documents containing "key" of some referenced document. There is reason we don't use UNIDs. I want to initialize data source by this key value. So in Document ID property I write script to open view, look up specified document and use looked up UNID to initialize data source.
I think this is not optimal solution.
Question: is there a better way to initialize document data source based on key value?
Sample code:
#DbLookup("", "view", "key", 1, '[RETURNDOCUMENTUNIQUEID]');
Looking up the document's UNID by key in a view is probably indeed the best way to do it. However, you could speed up repeated calls a bit by writing a managed bean to act as a cache. If, for example, you wrote a Java class that implements java.util.Map, stub out most of the methods, and implement a .get(...) method that takes the key as a parameter, you could reference it like (assuming you call the bean "DocKeyManager"):
<xp:dominoDocument ... documentId="${DocKeyManager[someKey]}"/>
That way, you could cache the value from the .get(...) call and not have to hit the database each time, and it'd also let you change the lookup algorithm later.
You should take a look at Tims article about converting strings to MD2.
this way I think you can convert your string id's to a unid and access them using getDocumentByUnid
http://xmage.gbs.com/blog.nsf/SearchResults?OpenNavigator&Query=md2
We do this a lot, but just remember to do the lookup once (on page load via the $ tag) instead of dynamic (# tag).
If you do it dynamic it will end up doing multiple lookups . . .
The suggestion from Jesse Gallagher to cache lookup results is also a good idea.

Multiple cells with multiple textfields to core data attributes

I have a tableview with 9 cells and in each cell i have at least 2 textfields. Each cell has a label, and the textfields.placeholder are the same in each cell:(example foto below)
I already created the entities in core data (which are the labels) and the attributes for each one ( which are the textfields.placeholder):
My question is, how can i set the textfield.text to each attribute in each entity? how to distinguish the textfields?....i don´t think that the IF statment is the best approach ( it would be a LOT!!), and the other problem is the cells are dynamic ( so the user can add more kind of trousers for example)...
Any ideas would be most appreciate... i´m really stuck!.
Thanks in advance.
I´ve been reading a little, but i´m having trouble understanding something: When you say "you can set an object for each cell" are your referring to the classes that core data automatically creates for each entity(when you hit subclass NSmanageobject button),and then i should bind the texfields from each cell to an object of each entity class??.I already have the classes that are referring to each cell, and then i think i should be doing this: Trousers *trouse = [NSEntityDescription insertNewObjectForEntityForName:#"Trousers" inManagedObjectContext:self.managedObjectContext]; trouse.nameProduct =Textfield.text.and this is the part i don´t no the best approach, because i have more than one textfield in each cell(and i din´t make them property´s of my view) and doing like this, it will be an enourmous amount of work! Can you help me understand better?.
If you are using CoreData with a table view you should be hooking up model objects to the UI using NSFetchedResultsController
Have a look at the documentation and examples for this. It's designed to make this sort of thing less painful.

Default Sort of tr:table?

Is there a way to sort the initial data displayed on UI using tr:table? I know there are sort properties which can be defined on tr:column and which are used to sort the data present in the table.
But the requirement here is to have the data sorted by default when the page is opened. Is there a way to do that except sorting the table data from back end?
You can't sort a table by default, but you have to do it programmatically. With a little bit of work you can write a reusable PhaseListener which you can control from your JSF page.
Make sure it only handles a single phase (for example PhaseId.RESTORE_VIEW) and use it to set the sort order using setSortCriteria:
List<SortCriterion> sortCriteria = new ArrayList<SortCriterion>(1);
String property = "myProperty";
boolean ascending = true;
sortCriteria.add(new SortCriterion(property, ascending));
myCoreTable.setSortCriteria(sortCriteria);
Now you only have to add two <f:attribute/>s on your table to pass both the property name and the ascending boolean so you can create a reusable listener for all your tables.
In your <tr:document> you can have a <f:attribute/> with a list of table ID's to process.
as far as I know: No!
You can read from here for more information:
"TRINIDAD-1491"

Core Data Document-based application: How do I model and control a entity that is instantiated only once per document?

I've got a few questions I've been trying to answer for myself (by hunting through the documentation) but I have a feeling I'm missing something.
Any hints (and/or pointers to appropriate documentation) would be much appreciated.
I'm building a Core Data document-based application. There are essentially two entities:
There is a single "Comparison" record associated with each document.
There are potentially many "Node" records associated with each document.
My first question is whether I'm thinking about this correctly. Since there is only a single Comparison object for each document, the attributes of the Comparison are essentially attributes of the Document itself. What (if any) is the preferred way of modeling that?
If a Comparison entity is in fact the right way to go, my next question is how and when to actually instantiate the (single) Comparison object. The user should not have to explicitly "add" the Comparison since there's going to be only one of them associated with the Document. Instead, a single Comparison object should be instantiated and inserted into the managedObjectContext. I've got something like this working already, with code in MyDocument.m that looks like this:
(void)windowControllerDidLoadNib:(NSWindowController *)windowController {
[super windowControllerDidLoadNib:windowController];
[NSEntityDescription insertNewObjectForEntityForName:#"Comparison" inManagedObjectContext:managedObjectContext];
}
However -- if the user creates a new document but then never does any work with it -- for example if he immediately clicks the close button -- then he should not be asked to "Save" the document. He should be asked to save his work only if he's actually entered any information. Is there a preferred way to implement this behavior?
I found this thread while struggling with the exact same issue. I have a table of Entity_A working in my document based Core Data app, but I need to figure out how to handle a required single-instance per document of Entity_B.
I've found something that seems to work. There's probably a better way, but this is getting me past this hurdle for now.
When the document's xib is loaded I simply check to see if an Entity_B has been created. if not, I create one and initialize its attributes.
- (void)windowControllerDidLoadNib:(NSWindowController *)aController
{
[super windowControllerDidLoadNib:aController];
//has an Entity_B been created? if not, create one.
NSError *theError = nil;
NSUInteger count = [[self managedObjectContext] countForFetchRequest:[NSFetchRequest fetchRequestWithEntityName:#"Entity_B"] error:&theError];
if( count == 0 )
{
NSManagedObject *newEntity_B = [NSEntityDescription insertNewObjectForEntityForName:#"Entity_B" inManagedObjectContext:[self managedObjectContext]];
[newEntity_B setValue:[NSNumber numberWithBool:YES] forKey:#"boolAttribute"];
[newEntity_B setValue:[NSNumber numberWithInt:2] forKey:#"intAttribute"];
}
}
I didn't insert that code snippet into the original post correctly. Trying again:
-(void)windowControllerDidLoadNib:(NSWindowController *)windowController {
[super windowControllerDidLoadNib:windowController];
[NSEntityDescription insertNewObjectForEntityForName:#"Comparison" inManagedObjectContext:managedObjectContext];
}
Your question about modelling is not very clear, can you please elaborate on what your "Comparison" entity is supposed to do and what sort of attributes you are assigning to it? It would be handy to see your "Document" entity structure so we can provide some useful input.
With regards to your second question, you could check if your NSManagedObject has been updated before deciding on whether to prompt the user to save their document or not:
if ([documentObject isUpdated]) {
...
}
More details in the documentation here http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObject_Class/Reference/NSManagedObject.html#//apple_ref/occ/cl/NSManagedObject
Cheers,
Rog
There isn't really a "Document" entity, I was simply using that term to refer to the overall document that is saved when the user invokes the Save menu item. Perhaps there is a better way to refer to this concept? NSPersistentDocument?
Backing up a bit... the central idea of the application is to compare two hierarchical directory structures (a visual recursive "diff").
For now the "Comparison" entity has two string attributes, pathA and pathB, which are the names of the two directories to be compared. Each "Node" entity represents the name of a file down in the directory trees that are being compared. The Node entity contains at least one attribute ("relativePath") which is the path relative to the starting point specified in the Comparison.
My first question was simply whether it makes sense for there to be a "Comparison" entity since there is going to be only one of them instantiated (at some point after the user invokes the "New" menu item).
The second question is really at what point should the single "Comparison" object be instantiated and inserted into the managedObjectContext, i.e. what method is most appropriate to make this happen?
Finally if a "Comparison" object is automatically instantiated (at awakeFromNib time, perhaps?) but the user decides not to proceed, and simply clicks the close button, he should not be prompted to save (right?) What would be the appropriate way to accomplish this? The documentObject will appear to have been updated, because an "empty" Comparison object has in fact already been inserted automatically at startup, but the user has not modified it.
Hope that's clear... thanks.

NSArrayController that is sorted and unique (no duplicates) for use in a pop-up in a core-data app

I have core data app with an entity OBSERVATION that has as one of its attributes DEALNAME.
I want to reference through Interface Builder or by making custom modifications to an NSArrayController a list of unique sorted dealnames so that I can use them in a pop-up.
I have attempted to use #distinctUnionOfSets (and #distinctUnionOfArrays) but am unable to locate the proper key sequence.
I can sort the ArrayController by providing a sort descriptor, but do not know how to eliminate duplicates.
Are the #distinct... keys the right methodology? It would seem to provide the easiest way to optimize the use of IB.
Is there a predicate form for removing duplicates?
Or do I need to use my custom controller to extract an NSSet of the specific dealnames, put them back in an array and sort it and reference the custom array from IB?
Any help would be appreciated. I am astounded that other have not tried to create a sorted-unique pop-up in tableviews.
You need to take a look at -[NSFetchRequest returnsDistinctResults]. That is the level you need to be handling the uniquing of data.
Although I do not have a definitive answer for you, I think there are two ways you can go about it.
The way you already started. You need to bind the contents array of the PopUp button, not just against the arrayController.arrangedObjects, but continue on the path and somehow filter only objects with distinct "DealName"s. This means - the arrayController presents ALL the entities (and may sort them for you) but the PopUp button will have its contents filter via some sophisticated binding to the array controller.
Make your filtering at the ArrayController level (as suggested in another answer here). Here it depends how you set up the array controller. If It is set up to use an "Entity" (vs. "Class") which means the array controller will fetch CoreData entities directly - you can modify its "Fetch" to only bring a subset of the "OBSERVATION" entities with distinct values of "DEALNAME". I don't know how to control WHICH entities are filtered out in this case. Otherwise, you can setup the arrayController to work with "Class" objects, and then you can fetch the entities yourself (in code) and populate the arrayController programmatically, with just the entities you like.
In the second option, the Popup button should be bound normally to the arrayController's arrangedObjects.

Resources