I am working on Core Data
for the first time.
I have just created an Entity
and Attributes
for that entity. I want to add some rows as da
You add data to a entity without an associated custom NSManagedObject subclass as follows:
NSManagedObject *mo = [NSEntityDescription insertNewObjectForEntityForName:@"MyEntityName"
inManagedObjectContext:aManagedObjectContext];
[mo setValue:aValue forKey:@"aKeyName"];
id aValue=[mo valueForKey:@"aKeyName"];
Core Data is not a table database. It is an object graph management system. As such, you deal with data within Core Data by changing the attributes of objects.
In the above example, I am changing the value held by the mo
instance which is a generic NSManagedObject. Because mo
is a generic NSManagedObject I use the setValue:forKey
to store the value within NSManagedObject's associative storage. The key names are set by the entities you create in the data modeler.
More commonly, you would create a dedicated NSManagedObject subclass whose attributes are the attributes and relationships of the entity. In that case the code above would look like:
MyManagedObjectSubclass *myMO = [NSEntityDescription insertNewObjectForEntityForName:@"MyEntity"
inManagedObjectContext:aManagedObjectContext];
myMo.attributeName=aValue;
id anotherValue=myMo.attributeName;
Trying to think of Core Data in SQL terms will only lead to grief. Core Data does not work like SQL. It works like a highly interconnected set of custom objects. You need to think in objects for Core Data, not tables.