基于返回 NULL 的关系的核心数据属性
Posted
技术标签:
【中文标题】基于返回 NULL 的关系的核心数据属性【英文标题】:Core Data properties based upon relationships returning NULL 【发布时间】:2015-06-15 12:48:38 【问题描述】:我有一个 Core Data 数据模型,例如
我想在我的 UITableViewCell 中显示与每个 Batting 对象关联的 Teams.name。当我尝试访问 batting.teams.name 时,它返回 NULL。
我的打开视图控制器传入了一个字符串,然后使用基于 Master.nameLast 的 NSPredicate 创建一个新的视图控制器,并列出所有匹配的名称
以及创建上述列表的 NSFetchedResultsController
#pragma mark - Fetched Results Controller Section
- (NSFetchedResultsController *)fetchedResultsController
if(_fetchedResultsController != nil)
return _fetchedResultsController;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Master" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"debut" ascending:YES];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"nameLast = [c]%@", lastName];
[fetchRequest setPredicate:predicate];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
fetchRequest.sortDescriptors = sortDescriptors;
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
return _fetchedResultsController;
然后,我的下一个视图控制器会列出与选定的 Master NSManagedObject 关联的所有 Batting 属性。
但是当我尝试访问 batting.teams.name 时,它返回 NULL !!!!!!如果我 NSLog 来自我的代表的实体,它们已设置,但我无法从它的 Batting.teams 关系中访问 Teams.name
#pragma mark - Fetched Results Controller Section
- (NSFetchedResultsController *)fetchedResultsController
if(_fetchedResultsController != nil)
return _fetchedResultsController;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Batting" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"yearID" ascending:YES];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"playerID = %@ " , selectedMaster.playerID];
[fetchRequest setPredicate:predicate];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
fetchRequest.sortDescriptors = sortDescriptors;
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
return _fetchedResultsController;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"playerStats" forIndexPath:indexPath];
Batting *batting = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSString *team = batting.teams.name; //NULL NULL NULL
// Configure the cell...
double average = [batting.h doubleValue]/[batting.ab doubleValue];
NSString *averageStr = [[NSString stringWithFormat:@"%.3f", average] substringFromIndex:1];
cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", batting.yearID, batting.teams.name];
cell.detailTextLabel.text = [NSString stringWithFormat:@"H: %@, AVG: %@, HR: %@, RBI: %@, SB: %@, R: %@, BB: %@, K: %@",
batting.h, averageStr , batting.hr, batting.rbi, batting.sb, batting.r, batting.bb, batting.so];
cell.detailTextLabel.textColor = [UIColor grayColor];
return cell;
为第二个参数返回 null??????????
cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", batting.yearID, batting.teams.name];
这是从 AppDelegate 记录的 Teams 实体
//
// AppDelegate.m
// Baseball Stats
//
// Created by Jason Steindorf on 6/6/15.
// Copyright (c) 2015 Jason Steindorf. All rights reserved.
//
#import "AppDelegate.h"
#import "Master.h"
#import "Teams.h"
#import "Batting.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
// Override point for customization after application launch.
NSError *error;
NSString* dataPath_MASTER = [[NSBundle mainBundle] pathForResource:@"master" ofType:@"json"];
NSArray* MASTER = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_MASTER]
options:kNilOptions
error:&error];
NSString* dataPath_TEAMS = [[NSBundle mainBundle] pathForResource:@"teams" ofType:@"json"];
NSArray* TEAMS = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_TEAMS]
options:kNilOptions
error:&error];
NSString* dataPath_ABC = [[NSBundle mainBundle] pathForResource:@"abc" ofType:@"json"];
NSArray* BATTING_ABC = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_ABC]
options:kNilOptions
error:&error];
NSString* dataPath_DEFGH = [[NSBundle mainBundle] pathForResource:@"defgh" ofType:@"json"];
NSArray* BATTING_DEFGH = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_DEFGH]
options:kNilOptions
error:&error];
NSString* dataPath_IJKLM = [[NSBundle mainBundle] pathForResource:@"ijklm" ofType:@"json"];
NSArray* BATTING_IJKLM = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_IJKLM]
options:kNilOptions
error:&error];
NSString* dataPath_NOPQR = [[NSBundle mainBundle] pathForResource:@"nopqr" ofType:@"json"];
NSArray* BATTING_NOPQR = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_NOPQR]
options:kNilOptions
error:&error];
NSString* dataPath_ST = [[NSBundle mainBundle] pathForResource:@"st" ofType:@"json"];
NSArray* BATTING_ST = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_ST]
options:kNilOptions
error:&error];
NSString* dataPath_UVWXYZ = [[NSBundle mainBundle] pathForResource:@"uvwxyz" ofType:@"json"];
NSArray* BATTING_UVWXYZ = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath_UVWXYZ]
options:kNilOptions
error:&error];
// Test listing all Master from the store
NSFetchRequest *fetchRequestMaster = [[NSFetchRequest alloc] init];
NSEntityDescription *entityMaster = [NSEntityDescription entityForName:@"Master" inManagedObjectContext:self.managedObjectContext];
[fetchRequestMaster setEntity:entityMaster];
NSArray *fetchedObjectsMaster = [self.managedObjectContext executeFetchRequest:fetchRequestMaster error:&error];
NSLog(@"Number of records in master.json - %d", (int)[fetchedObjectsMaster count]);
for (id m in MASTER)
Master *master = [NSEntityDescription insertNewObjectForEntityForName:@"Master"
inManagedObjectContext:self.managedObjectContext];
master.nameFirst = [m objectForKey:@"nameFirst"];
master.nameLast = [m objectForKey:@"nameLast"];
master.debut = [m objectForKey:@"debut"];
master.playerID = [m objectForKey:@"playerID"];
NSError *error;
if (![self.managedObjectContext save:&error])
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
fetchedObjectsMaster = [self.managedObjectContext executeFetchRequest:fetchRequestMaster error:&error];
for (Master *master in fetchedObjectsMaster)
NSLog(@"first name: %@", master.nameFirst);
NSLog(@"last name: %@", master.nameLast);
NSLog(@"debut: %@", master.debut);
NSLog(@"playerID: %@\n\n", master.playerID);
// Test listing all Master from the store
NSFetchRequest *fetchRequestTeams = [[NSFetchRequest alloc] init];
NSEntityDescription *entityTeams = [NSEntityDescription entityForName:@"Teams" inManagedObjectContext:self.managedObjectContext];
[fetchRequestTeams setEntity:entityTeams];
NSArray *fetchedObjectsTeams = [self.managedObjectContext executeFetchRequest:fetchRequestTeams error:&error];
NSLog(@"Number of records in teams.json - %d", (int)[fetchedObjectsTeams count]);
for (id t in TEAMS)
Teams *team = [NSEntityDescription insertNewObjectForEntityForName:@"Teams"
inManagedObjectContext:self.managedObjectContext];
team.name = [t objectForKey:@"name"];
team.minYearID = [t objectForKey:@"minYearID"];
team.maxYearID = [t objectForKey:@"maxYearID"];
team.teamID = [t objectForKey:@"teamID"];
NSError *error;
if (![self.managedObjectContext save:&error])
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
fetchedObjectsTeams = [self.managedObjectContext executeFetchRequest:fetchRequestTeams error:&error];
for (Teams *team in fetchedObjectsTeams)
NSLog(@"name: %@", team.name);
NSLog(@"minYearID: %@", team.minYearID);
NSLog(@"maxYearID: %@", team.maxYearID);
NSLog(@"teamID: %@\n\n", team.teamID);
NSFetchRequest *fetchRequestBatting = [[NSFetchRequest alloc] init];
NSEntityDescription *entityBatting = [NSEntityDescription entityForName:@"Batting" inManagedObjectContext:self.managedObjectContext];
[fetchRequestBatting setEntity:entityBatting];
NSArray *fetchedObjectsBatting = [self.managedObjectContext executeFetchRequest:fetchRequestBatting error:&error];
NSLog(@"Number of records in battingFiles.json - %d", (int)[fetchedObjectsBatting count]);
for (id b in BATTING_UVWXYZ)
Batting *batting = [NSEntityDescription insertNewObjectForEntityForName:@"Batting"
inManagedObjectContext:self.managedObjectContext];
batting.playerID = [b objectForKey:@"playerID"];
batting.h = [b objectForKey:@"h"];
batting.ab = [b objectForKey:@"ab"];
batting.hr = [b objectForKey:@"hr"];
batting.rbi = [b objectForKey:@"rbi"];
batting.sb = [b objectForKey:@"sb"];
batting.r = [b objectForKey:@"r"];
batting.bb = [b objectForKey:@"bb"];
batting.so = [b objectForKey:@"so"];
batting.yearID = [b objectForKey:@"yearID"];
batting.teamID = [b objectForKey:@"teamID"];
NSError *error;
if (![self.managedObjectContext save:&error])
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
fetchedObjectsBatting = [self.managedObjectContext executeFetchRequest:fetchRequestBatting error:&error];
for (Batting *b in fetchedObjectsBatting)
NSLog(@"playerID: %@", b.playerID);
NSLog(@"h: %@", b.h);
NSLog(@"ab: %@", b.ab);
NSLog(@"hr: %@", b.hr);
NSLog(@"rbi: %@", b.rbi);
NSLog(@"sb: %@", b.sb);
NSLog(@"r: %@", b.r);
NSLog(@"bb: %@", b.bb);
NSLog(@"so: %@", b.so);
NSLog(@"yearID: %@", b.yearID);
NSLog(@"teamID: %@\n\n", b.teamID);
return YES;
- (void)applicationWillResignActive:(UIApplication *)application
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
- (void)applicationDidEnterBackground:(UIApplication *)application
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
- (void)applicationWillEnterForeground:(UIApplication *)application
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
- (void)applicationDidBecomeActive:(UIApplication *)application
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
- (void)applicationWillTerminate:(UIApplication *)application
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
#pragma mark - Core Data stack
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (NSURL *)applicationDocumentsDirectory
// The directory the application uses to store the Core Data store file. This code uses a directory named "steindorf.Baseball_Stats" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
- (NSManagedObjectModel *)managedObjectModel
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedObjectModel != nil)
return _managedObjectModel;
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Baseball_Stats" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil)
return _persistentStoreCoordinator;
// Create the coordinator and store
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Baseball_Stats.sqlite"];
NSLog(@"%@", storeURL);
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
// Report any error we got.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
return _persistentStoreCoordinator;
- (NSManagedObjectContext *)managedObjectContext
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
if (_managedObjectContext != nil)
return _managedObjectContext;
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator)
return nil;
_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
#pragma mark - Core Data Saving support
- (void)saveContext
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil)
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
@end
【问题讨论】:
您是将上下文实例从 AppDelegate 传递到视图控制器,还是创建一个新实例?您需要来自 AppDelegate 的上下文。 - (NSManagedObjectContext *)managedObjectContext return [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 我要问一个明显的问题,你是在给球队对象分配击球对象对吧?你的球队已经设置好了,你的击球属性也设置好了,但是你是否设置了它们之间的关系? 实际上,我不这么认为。我添加了我的 AppDelegate.m 来展示我是如何创建一切的。你能看看这个并告诉我我错过了什么 【参考方案1】:在下面的块中,您需要指定球队进行击球。
batting.teams = your_team_object
然后您将能够访问团队信息。您可以使用 teamID 创建另一个对 Core Data 的提取来检索团队对象。
for (id b in BATTING_UVWXYZ)
Batting *batting = [NSEntityDescription insertNewObjectForEntityForName:@"Batting"
inManagedObjectContext:self.managedObjectContext];
batting.playerID = [b objectForKey:@"playerID"];
batting.h = [b objectForKey:@"h"];
batting.ab = [b objectForKey:@"ab"];
batting.hr = [b objectForKey:@"hr"];
batting.rbi = [b objectForKey:@"rbi"];
batting.sb = [b objectForKey:@"sb"];
batting.r = [b objectForKey:@"r"];
batting.bb = [b objectForKey:@"bb"];
batting.so = [b objectForKey:@"so"];
batting.yearID = [b objectForKey:@"yearID"];
batting.teamID = [b objectForKey:@"teamID"];
NSPredicate *teamIDPredicate = [NSPredicate predicateWithFormat:@"teamID == %@", [b objectForKey:@"teamID"]];
[fetchRequestTeams setPredicate:predicate];
NSArray *fetchedSpecificTeam = [self.managedObjectContext executeFetchRequest:fetchRequestTeams error:&error];
batting.teams= [fetchedSpecificTeam objectAtIndex:0];
NSError *error;
if (![self.managedObjectContext save:&error])
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
【讨论】:
我的 your_team_object 会是什么。我怎么做这个?我会制作一个 NSSet 并将每个 Team *teams 添加到其中吗 谢谢,我将重建并保存已连接的关系。一旦我可以测试生病让你知道。无论如何,再次感谢您为我指明正确的方向。 嗯,有时它似乎工作。我附加了一个日志,显示多个对象的相同 teamID 值,但名称有时仍然为空 不确定这是否是您问题的根源,但您的谓词中需要 ==。 我尝试了两种方式,我也尝试过使用和不使用 NSSortDesriptor。奇怪的是,有些记录如何设置正确的 teams.name,而有些记录在具有相同的 teamID 时返回 null。此外,当我搜索似乎正确设置了 teams.name 的玩家时,viewController 仍然在 tableviewcell 中列出(null)以上是关于基于返回 NULL 的关系的核心数据属性的主要内容,如果未能解决你的问题,请参考以下文章
核心数据中的 Fetched Property 返回不正确的计数