Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data NSSet returning empty array of objects

UPDATE: I had ghost entries in my database of games without players from before I implemented Players at all. It was returning those entries not the latest entries with the updated Model

I am working to get a Core Data database working and having some trouble with relationships. I'm very new to the whole thing so don't put anything past me I may no even understand the basics. But here we go anyway.

This is where I create a new Game Entity. The Players is a to-may relationship to Several Player entities that were selected and stored in an array.

    Game *newGame = [NSEntityDescription insertNewObjectForEntityForName:@"Game" inManagedObjectContext:[SDDataManager dataManager].managedObjectContext];
    [newGame setGameType:@"multipleChoice"];
    [newGame setDate:[NSDate date]];
    NSSet *playersSet = [NSSet setWithArray:players];
    [newGame setPlayers:playersSet];
    [newGame setCards:[NSKeyedArchiver archivedDataWithRootObject:selectedCards]];

    NSError *error;
    [[SDDataManager dataManager].managedObjectContext save:&error];
    NSLog(@"New Game Error: %@",[error localizedDescription]);

The problem is that when I call it out of the database like this:

NSFetchRequest *requestSavedGame = [NSFetchRequest fetchRequestWithEntityName:@"Game"]; [requestSavedGame setFetchLimit:1];

NSError *error;
NSArray *loadedGame = [[SDDataManager dataManager].managedObjectContext executeFetchRequest:requestSavedGame error:&error];
NSLog(@"Load Game Error: %@",[error localizedDescription]);

Game *game = [loadedGame objectAtIndex:0];
NSLog(@"Players Set: %@",game.players);
NSLog(@"Players: %@",[game.players allObjects]);

The Players: is empty?? It returns this exactly:

Players Set: Relationship 'players' fault on managed object (0xd023b70) <Game: 0xd023b70> (entity: Game; id: 0xd023180 <x-coredata://E6A82377-31D2-4D11-B890-B3FDC5A03E0E/Game/p1> ; data: {
cards = <62706c69 73743030 d4010203 0405086e 6f542474 6f705824 6f626a65 63747358 24766572 73696f6e 59246172 63686976 6572>;
currentPlayer = 0;
date = "2012-03-27 18:20:07 +0000";
gameType = multipleChoice;
players = "<relationship fault: 0xd01fd60 'players'>";
})

Players: ( )

I have no understanding why the players is a full array, then a full set when it goes in but when it comes out the [set allobjects] returns an empty array...

like image 298
Ryan Poolos Avatar asked Dec 13 '25 15:12

Ryan Poolos


1 Answers

I would suggest you to use valueForKey for whatever key.

In core data fault is not an error, it means you are trying to access from core data which does not exist. and i would say you should use setPropertiesToFetch which specifies which properties should be returned by the fetch.

like image 116
Praveen-K Avatar answered Dec 16 '25 09:12

Praveen-K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!