Core Data and uniquing?

Either I'm not understanding what the term "uniquing" means in Core Data, or I'm not fetching my data properly. I have a pretty simple data model. Three entities: Community, Asset, and Category. Each Community has a relationship to multiple categories. Each category has a relationship to multiple assets. Each asset that is created must have one and only one category.
In the code I've posted, I'd like to output all the categories that a specific community has into the console. I thought that because of Core Data's uniquing capability, only one category of the same name could exist at a time (name is the only attribute for a category). However, when I print to the console, I'm getting duplicate category names.
// Fetch Community instances in the database, and add them to an NSMutableArray
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *community = [NSEntityDescription entityForName:@"Community" inManagedObjectContext:managedObjectContext];
[request setEntity:community];
// Only return the community instances that have the cityName of the cell tapped in the CommunitiesNonEditableTableViewController
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(cityName like %@)", cellCityName];
[request setPredicate:predicate];
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
// Set communitiesArray with mutableFetchResults
[self setCommunitiesArray:mutableFetchResults];
[mutableFetchResults release];
[request release];
// Creates a community instance using the community stored in the array at index 0. This is the only community in the array.
Community *communityInstance;
communityInstance = [communitiesArray objectAtIndex:0];
// Retrieves existing categories of assets in the community, and adds them to an NSSet
NSSet *communityCategoriesSet = communityInstance.categories;
// Converts NSSet to an NSArray with each category as an index
NSArray *communityCategoriesArray = [communityCategoriesSet allObjects];
// For loop that iterates through the array full of categories, retrieves the names of each category, and adds it to an NSMutableArray
categoryNames = [[NSMutableArray alloc] init];
int i;
for (i = 0; i < [communityCategoriesArray count]; i++) {
Category *categoryInstance;
categoryInstance = [communityCategoriesArray objectAtIndex:i];
[categoryNames addObject:categoryInstance.name];
// Prints array full of category names to console
NSLog(@"%@", categoryNames);
When I execute this, I get duplicate names in the console. Why?
Thanks for the help!

You need to set the name as a key or specify unique when creating the table and that column. Generally it is bad to use a city name as a unique id, since there are many cities with the same name (Middletown) in different states. You should use a number, autoincrement, as the id.

Similar Messages

  • Core data and predicate on large volume

    Hi,
    In one of my current project requirement is to view product information in perticular date range.
    Input
    No. Of products  :- P1 P2 P3 P4 P5
    No of channels....:-  C1 C2 C3 C4
    No of regions     :- R1 R2 R3 R4
    Depending on any of the above combination user can select either "Daily" "Weekly" "Monthly" "Yearly"
    for daily for Perticular date there will be (5 produtcts *4 channel*4 regions)= 80 Combinations
    Daily :-so for 5 years it will be (80*365*5=1,46, 000) records
    Montly:- for monthly for 5 years :- 12 *5 = 60 so total 4800 records.
    quarterly for quarterly for 5 years :- 4 *5 = 20 so total (20*80) =1600 records.
    That means we can calculate all daliy monthly , quarterly and yerly using daily data.
    As user can varies the selected combination of product , channels and regions and can also slect the date range.
    Looking at the search criteria , we decided to load the data into core data and then use predicate to fetch teh data.
    Calculation formula:-
    Day :- On perticular date
    Weekly :- On friday i.e. end of week
    Monthly :- 31/30 month end date
    Quarterly :- March end date , Jun end date etc.
    Yearly 31st dec date
    But my questoion is ,
    1.Can we  use Daily model to fetch also monthly , quaterly and yearly information. Memory optimization good vs response time less
    2. Sepaarte data model for Daily , Monthly and quarterly . Yearly we can calculate from quarterly . [Response time good but duplicate data]
    Could anyone plesae suggest which is the best option to model this data ?

    Does this help?

  • Core Data and Postgres merger?

    Hello!
    Is there some public info or "big picture" available how to or where to hook myself into the object and message chain of Core Data and to generate SQL to CRUD (Create, Read, Update, Delete) rows of data with postgres instead of SQL Lite or flat-files that Core Data natively supports?
    I also like the ActiveRecords way of doing things in Ruby and an Objective-C class, that models a table and objects model single rows, doesnt seem too overtly complicate to implement, but how to bind this then effectively with Core Data? So that we could use CoreData models nicely in IB and use the available binding methods.
    Thanks for any input,
    regards
    Philipp
    Intel iMac   Mac OS X (10.4.6)  

    Does this help?

  • Problem with core data and attribute name "description"

    I have spent hours tying to figure out this problem.
    It appears that is you name an attribute "description", there can be problems at run-time.
    Perhaps, it is related to how I am doing things and letting interface builder do all the bindings.
    I create a core data application in Xcode.
    I create the entity with some attributes in Xcode and then I launch interface builder. I drag a "core data entity" object to the application window. I add a "Master/Detail View".
    I save the files and do a compile. When I click on the "add" button, something goes wrong and GDB launches and loads the stack frame into the debugger.
    I am using Xcode 3.1.2.

    description is the name of a method in the NSObject protocol; try to use another name for your attribute in CoreData, for example myDescription.

  • Core data and Populate field programmatic

    Hi
    On a window i have a couple of controls Combo box, Text field and a few buttons
    all linked to core data which is working perfect ish
    if I select the combo box and change the value its updated in core data straight away
    if I press a button it put a value in the text box but doesn't update the code data field until i click in the field and add a space or something simular ..
    is it a focus thing, the field don't lose focus until I have done it manually
    can someone point me in the right direction for this
    just want to click a button , put that value in the textbox and core data is updated without having to click in the text box
    regards
    Tony

    Does this help?

  • Core Data and Xcode 4

    It seems as if there are some very important parts of the Core Data data model editor missing, namely setting up "To Many" relationships, and setting the deletion rules.
    Where do you do this in Xcode 4?

    nevermind, I've found it. For anyone else looking, you must have the Utility View open (the left-side view from the top bar), And have it set to "Show Data Model Inspector" (on my screen, the 3rd of the top icons on the utility view)
    Kinda frustrating that it's so hidden...

  • Core Data and migration question.

    Lets say software v1.0 uses the core data model version coreDataModelA.xcdatamodel ...
    Software v2.0 uses core data model version coreDataModelB.xcdatamodel...
    and Software v3.0 uses core data model version coreDataModelC.xcdatamodel.
    Assuming migrations were done from coreDataModelA.xcdatamodel to coreDataModelB.xcdatamodel and then to coreDataModelC.xcdatamodel, if a user is upgrading from software version 1.0 to software version 3.0 (skipping 2.0).... will it successfully migrate for them?
    I'm assuming an app has only one xcmappingmodel file.

    Does this help?

  • Core Data and Cocoa Binding

    Hello,
    I'm trying to make core data application and I refer to following url as test.
    http://developer.apple.com/cocoa/coredatatutorial/index.html
    However, I have following error.
    2011-03-04 00:32:01.476 XMLTest2CoreData[9954:a0f] An uncaught exception was raised
    2011-03-04 00:32:01.479 XMLTest2CoreData[9954:a0f] Cannot create BOOL from object (
    ) of class __NSArray0
    2011-03-04 00:32:01.481 XMLTest2CoreData[9954:a0f] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Cannot create BOOL from object (
    ) of class __NSArray0'
    * Call stack at first throw:
    0 CoreFoundation 0x00007fff87de97b4 __exceptionPreprocess + 180
    1 libobjc.A.dylib 0x00007fff852cd0f3 objcexceptionthrow + 45
    2 CoreFoundation 0x00007fff87de95d7 +[NSException raise:format:arguments:] + 103
    3 AppKit 0x00007fff84830e78 _NSBoolFromValue + 443
    4 AppKit 0x00007fff848309a9 -[NSEditableBinder _setStatesImmediatelyInObject:mode:triggerRedisplay:] + 554
    5 AppKit 0x00007fff84830778 -[NSEditableBinder _observeValueForKeyPath:ofObject:context:] + 116
    6 AppKit 0x00007fff84775a33 -[NSObject(NSKeyValueBindingCreation) bind:toObject:withKeyPath:options:] + 557
    7 AppKit 0x00007fff84752546 -[NSIBObjectData nibInstantiateWithOwner:topLevelObjects:] + 1172
    8 AppKit 0x00007fff8475088d loadNib + 226
    9 AppKit 0x00007fff8474fd9a +[NSBundle(NSNibLoading) _loadNibFile:nameTable:withZone:ownerBundle:] + 248
    10 AppKit 0x00007fff8474fbd2 +[NSBundle(NSNibLoading) loadNibNamed:owner:] + 326
    11 AppKit 0x00007fff8474d153 NSApplicationMain + 279
    12 XMLTest2CoreData 0x0000000100001089 main + 33
    13 XMLTest2CoreData 0x0000000100001060 start + 52
    terminate called after throwing an instance of 'NSException'
    Entity is only one "Title" and it has one attribute "name".
    My XCode is version 3.2.5.
    Please give me advice...
    Thank you.

    I have a new problem...
    I succeed to run the application, and save the data.
    But cannot open the saved data.
    In addition, The application doesn't ask anything as terminating it.
    I checked that I could save the data.
    </metadata>
    </databaseInfo>
    <object type="GENE" id="z102">
    <attribute name="name" type="string">PTEN</attribute>
    <attribute name="creationdate" type="date">321113984.72053700685501098633</attribute>
    <relationship name="mrna" type="1/1" destination="M_RNA"></relationship>
    <relationship name="protein" type="1/1" destination="PROTEIN"></relationship>
    <relationship name="title" type="1/1" destination="TITLE"></relationship>
    </object>
    <object type="TITLE" id="z103">
    <attribute name="name" type="string">PTEN</attribute>
    <relationship name="genelist" type="0/0" destination="GENE" idrefs="z102"></relationship>
    </object>
    </database>
    And I tried to check the log...
    but, I have only following message...
    2011-03-06 23:56:15.660 XMLTest2CoreData[14116:a0f] Application terminating.
    - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
    NSLog(@"Application terminating.");
    if (!managedObjectContext) {
    NSLog(@"managedObjectContext is nil...");
    return NSTerminateNow;
    if (![managedObjectContext commitEditing]) {
    NSLog(@"%@:%s unable to commit editing to terminate", [self class], _cmd);
    return NSTerminateCancel;
    if (![managedObjectContext hasChanges]) {
    NSLog(@"Application has not changed.");
    return NSTerminateNow;
    NSError *error = nil;
    if (![managedObjectContext save:&error]) {
    NSLog(@"Application terminating and attempting to save.");
    // This error handling simply presents error information in a panel with an
    // "Ok" button, which does not include any attempt at error recovery (meaning,
    // attempting to fix the error.) As a result, this implementation will
    // present the information to the user and then follow up with a panel asking
    // if the user wishes to "Quit Anyway", without saving the changes.
    Any advice would be helpful.
    Thank you.
    Message was edited by: Rascal3

  • Should I use Core Data?

    I'm starting a new document-based application. Is Core Data the way of the future, or just a convenience for specific types of apps? That is, in the "old days" you would override -[NSDocument dataOfType:] and readFromData: to archive your objects. It seems appealing to use Core Data and get automatic archiving in XML, SQL, and binary all for free, but the tutorials I've gone through all seem directed at a very different kind of app than mine. (Rather database-like, but I suppose the demo has to look like something.) The old "Sketch" example, which uses old-style archiving, hasn't been updated in years. Which direction to go?

    Look up HyperCard in Wikipedia for a good explanation. In short, I'm developing a GUI-based mini-app environment, where users can create buttons & fields, and hook them up with an elementary scripting language. I've written the compiler & interpreter, am starting the surrounding framework.
    "Have you looked at the Apple HIGs lately?" Dude, I was reading "Inside Macintosh" back in 1984.
    Mobile platform? Since I'm using garbage collection, I'm shut out of iPhone/iPad, at least for the time being.

  • Import Xml data into Core Data

    Hi im very new here, im trying to find a tutorial to import a xml data into a core data and so i can publish it in a tableview
    Can somebody help me??
    thanks

    Hi,
             If you have already have the xml data then you need to parse the XML data (Using NSXMLParser Class), After parsing the data we need to maintain arrays to store this XML content. After getting the arrays with fully parsed data, you have to store this data in our Local Database (Core Data).  May be it helps for you.
    http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation /Classes/NSXMLParser_Class/Reference/Reference.html

  • Core Data Issue

    I am creating a coredata sqlite database file in a mac app (using core data) and am attempting to use the same database and core data model in an ipad app.   I have copied all NSManagedObject files and the .xcdatamodeld directory from the mac app to the ios app.  Even though all files are identical I get "
    The model used to open the store is incompatible with the one used to create the store" when trying to read from the store in the app.  My question is what is actually being compared when this error is thrown?  It looks like it throws the error following SELECT Z_VERSION, Z_UUID, Z_PLIST FROM Z_METADATA.   What is a z_uuid?  Any ideas on how to debug this?   my error dump is below.
    2014-05-06 12:57:29.118 Genome[9055:60b] CoreData: sql: SELECT Z_VERSION, Z_UUID, Z_PLIST FROM Z_METADATA
    2014-05-06 12:57:29.119 Genome[9055:60b] CoreData: annotation: Disconnecting from sqlite database.
    2014-05-06 12:57:29.121 Genome[9055:60b] Unresolved error Error Domain=NSCocoaErrorDomain Code=134100 "The operation couldn’t be completed. (Cocoa error 134100.)" UserInfo=0x109527050 {metadata={
        NSPersistenceFrameworkVersion = 481;
        NSStoreModelVersionHashes =     {
            Annotation = <d4eb8bbc 528c6ac9 3cc1decb ca49790e 9933c09b faf47ec9 108fb9b4 b083e144>;
            Band = <14c5dda0 3db4c5c7 27952ce6 5421b597 6d97bed9 b6f225c7 0d956b54 2cfc8282>;
            Gene = <e70a2ed2 fa4c0c3e 1fb8eabc f0f1c26b 9dadb033 0c9198fe 9ba2393e c1a3f9c2>;
            Test = <051b8cd1 849daecf 7a94ac5a 87134d9b 1db8b51c 60bdca34 cb828268 01d6a73a>;
            User = <ebf4a8c8 7209296b 30bdf66c bd7a3dac afa9c8c5 d04f363f 14469686 ba458804>;
            Variant = <58231e33 52687ba7 053846d2 e8d27ed2 58ec690b 2fb09efc 303f299f 2592d6f5>;
        NSStoreModelVersionHashesVersion = 3;
        NSStoreModelVersionIdentifiers =     (
        NSStoreType = SQLite;
        NSStoreUUID = "9B3D312C-95C8-45E3-9F2F-2581E88403A8";
        "_NSAutoVacuumLevel" = 2;
    }, reason=The model used to open the store is incompatible with the one used to create the store}, {
        metadata =     {
            NSPersistenceFrameworkVersion = 481;
            NSStoreModelVersionHashes =         {
                Annotation = <d4eb8bbc 528c6ac9 3cc1decb ca49790e 9933c09b faf47ec9 108fb9b4 b083e144>;
                Band = <14c5dda0 3db4c5c7 27952ce6 5421b597 6d97bed9 b6f225c7 0d956b54 2cfc8282>;
                Gene = <e70a2ed2 fa4c0c3e 1fb8eabc f0f1c26b 9dadb033 0c9198fe 9ba2393e c1a3f9c2>;
                Test = <051b8cd1 849daecf 7a94ac5a 87134d9b 1db8b51c 60bdca34 cb828268 01d6a73a>;
                User = <ebf4a8c8 7209296b 30bdf66c bd7a3dac afa9c8c5 d04f363f 14469686 ba458804>;
                Variant = <58231e33 52687ba7 053846d2 e8d27ed2 58ec690b 2fb09efc 303f299f 2592d6f5>;
            NSStoreModelVersionHashesVersion = 3;
            NSStoreModelVersionIdentifiers =         (
            NSStoreType = SQLite;
            NSStoreUUID = "9B3D312C-95C8-45E3-9F2F-2581E88403A8";
            "_NSAutoVacuumLevel" = 2;
        reason = "The model used to open the store is incompatible with the one used to create the store";

    That is not it.  I acually had it working with Mavaricks and ios7 and then something changed.   I am wondering what exactly is being compared when the The model used to open the store is incompatible with the one used to create the store error is thrown.  It is obviously not the columns of the db and properties of the managed objects because they are identical.

  • Core data binding not working

    in my project I used core data and binding to produce data on document based program.
    I have used multiple entities and they worked fine and then they stopped working and I don't know why.
    all the text fields now have "()" in them with space in between them, and will not add to the database.  so the field shows a junk value and will not bind properly to the database.
    how would I start to debug this I have been searching but I don't know where to start, mainly i dont know what the problem is.

    Binding works one way. This means that textInput.text changes
    to match the value of account.identifier, not the other way around.
    While I think it's theoretically possible to create a binding the
    other way (I haven't played with binding in ActionScript), it makes
    more sense to listen to the TextInput's change event to get changes
    to the text field.
    Or, you can create a model in the MXML and bind one its
    properties to the textinput's value. Look in the docs about the
    mx:Model tag for details.

  • Core Data: Get Managed Object by unique part of the objectID

    In my Core Data application, I need to get the pointers to different managed objects whose CoreData objectIDs end with the number I provide. e.g.:
    Get the Person object whose objectID ends with unique number 317. The whole ID is:
    <x-coredata://A3EDF6C1-229D-4658-A04E-598ADF1C749A/Person/p317>
    or I need to get Department object, which ends with 5; again full ID is:
    <x-coredata://A3EDF6C1-229D-4658-A04E-598ADF1C749A/Department/p5>
    These numbers are actually primary keys in the SQLite database's tables and I can see them if I open the database directly with sqlite3, and I can of course select the records using SQL query;
    *but I can not figure out how to get these objects using CoreData. I guess I should create the NSPredicate for the fetch request; but I don't know how to write the predicate which will give me the exact object based on the unique part of the objectID*
    As I understand, objectIDs are not object's "normal" attributes.
    Please help. Thanks in advance.

    etresoft wrote:
    DavidMan wrote:
    *but I can not figure out how to get these objects using CoreData. I guess I should create the NSPredicate for the fetch request; but I don't know how to write the predicate which will give me the exact object based on the unique part of the objectID*
    I think you are supposed to consider the entire ID to be unique. You can retrieve the associated object using "objectWithID:" from NSManagedObjectContext.
    The problem is that I am parsing the text from another application and I have only the "unique part" at hand and not the whole objectID. So, I need to cope with that.
    What I see is that the IDs of every entity start with the same text, e.g. here are the IDs of two different entities:
    <x-coredata://A3EDF6C1-229D-4658-A04E-598ADF1C749A/Person/p317>
    <x-coredata://A3EDF6C1-229D-4658-A04E-598ADF1C749A/Department/p5>
    As you see, the difference is only in the end, after the entity names "Paper" and "Department". But this is my case and I am not completely sure that this will hold true for EVERY future installation on any system for every entity.
    *Question: will the part like <x-coredata://A3EDF6C1-229D-4658-A04E-598ADF1C749A be constant for the particular installation, for every entity/object?*
    If YES, then I will:
    - after getting any/first object, extract the non-unique part, i.e. <x-coredata...749A which is the same for every object in this particular installation on this particular computer
    - get the unique part, i.e. /Person/p317, /Person/p23, /Department/p5 etc.
    - synthesize the "real ID" by appending these two strings
    - ask managedObjectContext to return the object with this ID
    - continue with the acquired object
    How does it sound? Will this work on other computers?
    P.S. FYI: the coredata of this program has only one store i.e. all the data are stored in single sqlite file.

  • Edit and save a Core Data entity?

    Sorry if this is a fairly obvious issue, but I honestly can't find anything..
    Every sample Core Data application I've come across has examples of inserting and deleting entities/objects. But I cannot find anything about editing and saving some attributes of an existing object. Is this possible??
    I'm using default core data/managed objects, not custom classes yet. I can insert, view, and delete objects from the context. But I want to be able to edit attributes, and NOT in a table cell. I want to open the object in a separate window (which I can do), edit the attributes in that window, and click a "Save" button to update the attributes of that particular object. I can't find anything that shows me how.
    I am thinking a work-around would be to remove the existing object and just create a new object with the data, but if I have relationships to other objects, it seems like doing that would mess them up. My other train of thought is, if I can't do this with default core data objects, what CAN I do it with? Do I need to create custom classes for the objects, or do I need to use an SQL database separately?
    Thanks...

    Apple has this to say about that...
    Entity-relationship modeling is a way to describe data structures that can be mapped to an object-oriented system. Since it comes from the database world, there is some terminology that is associated with it that you may not be familiar with. These terms are:
    Entities, specific pieces of information in a data model.
    Attributes, the components of an entity. These are usually simple scalar types, such as int, float, or double; C structures such as char *, NSPoint; or an instance of a primitive class, such as NSString, or NSNumber.
    Relationships, references that an entity can have to other entities. These relationships can be optional or required as well as one-to-one or one-to-many.
    Properties, a collective term for attributes and relationships.
    -=-
    Entities and Managed Objects
    Each entity definition in a managed object model requires the name of the entity and the name of the class used at runtime to represent that entity.
    http://developer.apple.com/macosx/coredata.html
    do I need to use an SQL database separately?
    Core Data support three different kinds of data store formats to save managed objects contexts to. These formats are:
    • XML file format
    • Binary archive file format
    • SQLite database file format
    ...which are you using now? That is a rhetorical question for you to ponder, actually.

  • Core Data - Save and Load

    Hi
    I need to add functionality to my iPad app so that I can save and load notes from a UITextView then load them when the user selects the date in the UIDatePicker that it was originally saved on, much like a calendar, notes for different dates.
    I have asked around on StackOverFlow and people have been spoon feeding me code samples but I am not quite latching on. Complain all you like, but I really want to learn how to do this, however currently its fairly important that I get the functionality added in.
    Here is where I asked:
    http://stackoverflow.com/questions/4133405/core-data-iphone-save-load-depending- on-date
    http://stackoverflow.com/questions/4177398/save-and-load-data-coredata
    I have unsuccessful so far and if anyone can help me here I would be ever so grateful and even more so if you would take a short time to take a peek at my project. You can email me at [email protected], its a fairly simple project and Im sure especially for you guys you could see what I am doing.
    Hope you can help me out.

    Core Data pretty much does away with the concepts of saving and loading. The data is just there. If you want a particular view of data, on a specific date, for examples, you create a predicate to pull only the matching data into a particular controller/UI control.

Maybe you are looking for

  • Removing Apps from Mac and iPhone/iPad

    Hi all. Can someone advise the best way to completely remove unwanted apps please? The issue I have is that if I remove the app from my iPhone/iPad and then sync my phone with my iMac, the app just gets put back on the iPhone/iPad. If I remove it fro

  • Can't Create Two DW Instances so...what do you do?

    I understand you can't create two instances of Dreamweaver (unless you have an OS that runs mult instances) http://www.adobe.com/cfusion/webforums/forum/messageview.cfm?forumid=12&catid=189&threadid =1297532&highlight_key=y&keyword1=instances The rea

  • Aperture editing

    When using an external editor in aperture, it converts the image to .tiff. Is there an easy way to convert these back to .jpg other than exporting them as .jpg and reimporting them as .jpg. If I do this will I lose any of the edited image. What is be

  • Missing dll's on launch? (Nikon view dll's)

    I downloaded and seemingly-successfully installed PS CS5 on April 30th.  When I launch PS, however, I received an error "Can't find NEFLibrary3.dll".   After clicking "OK", PS completed launching and seemed to be working perfectly fine.  After some i

  • Extending 'People' Information in Portal

    We need to add additional columns to the information found in the 'persons (wwv_persons)' table in the portal. What is the best way to do this (add an additional table and link the two)? We are trying to capture/write portlets to maintain user inform