user2414460
user2414460

Reputation: 211

Reading Core Data as Objects

I have 1 entity in my database "Message" with the values MessageID, messageText and i want to read every row of Core Data, make an object of my class "Message" and put the new object into an array. It's the first time I'm using Core Data and I don't quite get it yet, how I manage to do that.

Upvotes: 2

Views: 101

Answers (2)

samir
samir

Reputation: 4551

The response of @Abizern with code :

NSManagedObjectContext *moc = // your managed object context;
NSEntityDescription *entityDescription = [NSEntityDescription
    entityForName:@"Message" inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];

// You can also add a predicate or sort descriptor to your request

NSError *error;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil)
{
    // Deal with error...
}

Upvotes: 0

Abizern
Abizern

Reputation: 150755

Create a fetch request for the entity you wish to retrieve. Don't give it a predicate, set whatever sort descriptor you want.

Execute the fetch request in a managed object context and it will return an array of all the objects of that entity.

This is purposely just a descriptive answer, you can find the specifics of how to do this from the Core Data introductory documentation; you are new in Core Data and this is a good way to learn it.

Also - don't think of Core Data in terms of rows of data that you turn into objects. It's an Object-Relationship graph. It stores the objects of entities and their relationships between them. You don't turn the "rows" into objects, you get the objects back directly.

Upvotes: 2

Related Questions