Question

I have the following Array which retrieved from the Core Data :

NSArray *dataArray = [context executeFetchRequest:request error:&error];

so I wrote this code to get each row data individually to send it to REST API:

for (NSString *str in dataArray) {

        NSString *name =[dataArray valueForKey:@"name"];
        NSString *dob = [dataArray valueForKey:@"dob"];
        int gender =[[dataArray valueForKey:@"gender"]integerValue];
        NSString *childId =[dataArray valueForKey:@"id"];

         int response = [network sendName:name withDateOfBirth:dob andGender:gender forID:childId];

        if (response == 200) {
            // [self performSelectorOnMainThread:@selector(postSuccess) withObject:nil waitUntilDone:YES];
            NSLog(@"Success");

        }
    }

but it's not working, because I couldn't know how data is stored in each index in the array!! Please help, and if I am not doing this correctly please tell me a better way to do it.

Thanks.

Was it helpful?

Solution

NSString *name =[dataArray valueForKey:@"name"];

This doesn't do what you think it'll do. valueForKey:, when sent to an array, returns an array of the values corresponding to the given key for all the items in the array. So, that line will assign an array of the "name" values for all the items in dataArray despite the fact that you declared name as a NSString. Same goes for the subsequent lines.

What you probably want instead is:

for (NSManagedObject *item in dataArray) {
    NSString *name = [item valueForKey:@"name"];
    ...

Better, if you have a NSManagedObject subclass -- let's call it Person representing the entity you're requesting, you can say:

for (Person *person in dataArray) {
    NSString *name = person.name;
    ...

which leads to an even simpler version:

for (Person *person in dataArray) {
    int response = [network sendName:person.name
                     withDateOfBirth:person.dob
                           andGender:person.gender
                               forID:person.id];

although I'd change the name of that method to leave out the conjunctions and prepositions. -sendName:dateOfBirth:gender:id: is enough, you don't need the "with", "and", and "for."

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top