简体   繁体   中英

Core Data Fetch Request is working on simulator but not on the device

I'm calling the below method from AppDelegate. Fetch Request is returning 0 records on the iPad device,please advise. Records are correctly returned on the simulator. I've confirmed that arguments passed are not nil on both device and simulator.

+ (Movie    * ) movieWithID : (NSString * ) ID withObjectContext:(NSManagedObjectContext *) context

{

    Movie *movie= nil;

    NSFetchRequest *request =[[NSFetchRequest alloc]init];

     NSLog(@"ID : %@ Context : %@", ID,context);
     // Context and ID are not nil on both simulator and device

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Movie" inManagedObjectContext:context];

    [request setEntity:entity];

    NSError *error =nil;

    NSArray * fetchResults = [context executeFetchRequest:request error:&error];
     //0 records are returned on the device
     //Correct number of records are returned on the simulator 


    if (entity && request) {

        NSLog(@"Fetch Count %d",[fetchResults count]);

    }

    else

    {

        NSLog(@"Entity is nil");

    }

    request.predicate = [NSPredicate predicateWithFormat:@"id like %@",ID];

     fetchResults = [context executeFetchRequest:request error:&error];

    if ([fetchResults count] > 1) {

        NSLog(@"Fetched Results > 1");

    }                              

    if (!fetchResults ) {
        NSLog(@"Fetch Failed");
    }

    else if ([fetchResults count]== 0) {

        NSLog(@"No movie results %@",error);

    }

    else if ([fetchResults count] ==1) {

        movie= [fetchResults lastObject];

    }

    return movie;

}

The reason must be that the store that is being queried is different on the iPad and on the simulator. Make sure you copy any prepared SQLite stores to the device correctly and verify that the data you are trying to fetch is really there.

One way to test this is to insert the data first in code. - You could then check if your fetch request is working.

You don't check the error after the fetch request(although you pass it as a parameter), if you'll check it I'm sure you'll get the reason behind your problem. Also, when you initialise the store, be sure to assert the errors too.

I had the same problem. My problem was based on the fetchrequest predicate. Because the predicate string was stored in iCloud key-value storage, it worked fine in the simulator that was not on iCloud. However, on my device, the predicate I had forgot was implemented in the fetchrequest, and gave no results.

This might not apply to you, but check your predicates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM