user2480376
user2480376

Reputation: 13

Fetch arrays of values in CoreData

In my XCode project, I have two entities for my CoreData. These entities are called Session and SessionDetails. Session has one attribute called timeCompleted (Type: Date) which is a time stamp of the event. Session is in a one-to-many relationship to SessionDetails but the attribute that is most important is averageDistance (Type: Float).

The Sessions are sorted using timeCompleted. I would like to fetch the averageDistance values of the sorted Sessions and place them in an array that could be used to generate a plot. The x-axis will have the date of the event and the y-axis will have the averageDistance value. I am not concerned right now with creating the plot but rather just extracting the values that will be used for it. Would appreciate any help!

Upvotes: 0

Views: 2427

Answers (2)

matthew
matthew

Reputation: 1

Maybe this could work in your case:

NSArray *sessions = ... // sorted array of Session objects

for (Session *session in sessions)
{
    NSDate *date = session.timeStamp; // you get the date

    NSSet *detailsSet = session.sessionDetails; // session.(details) or whatever the name of the relation is
    for (SessionDetails *details in detailsSet)
    {
        float averageDistance = details.averageDistance; // you get the average distance
        // collect your (date, averageDistance) pair here
    }
}

Upvotes: 0

Martin R
Martin R

Reputation: 539715

You can use Key-Value coding to get an array of attribute values. Assuming that averageDistance is an attribute of Session, you can do the following:

NSArray *sessions = ...; // Your sorted array of Session objects
NSArray *distValues = [sessions valueForKey:@"averageDistance"];

distValues is now an array of NSNumber objects containing the averageDistance from each Session object.

UPDATE: As it turned out in the discussion, there is a to-many relationship from Session to SessionDetails, averageDistance is an attribute of SessionDetails, and you need all possible (timeCompleted, averageDistance) pairs, sorted by timeCompleted.

Therefore, you should fetch all SessionDetails objects instead of fetching Session objects, and sort them according to timeCompleted of the related session:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SessionDetails"];
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"session.timeCompleted" ascending:YES];
[request setSortDescriptors:@[sort]];
NSArray *result = [context executeFetchRequest:request error:&error];

(I have assumed that you have an inverse relationship session from SessionDetails to Session.)

Now you can extract the timeCompleted and averageDistance value from these objects, using Key-Value Coding:

NSArray *xValues = [result valueForKeyPath:@"session.timeCompleted"];
NSArray *yValues = [result valueForKey:@"averageDistance"];

Upvotes: 2

Related Questions