我正在为我的应用程序使用 Core Data,但我目前遇到了这个问题。
我的应用程序在 Core Data 模型 2 实体上运行良好
UserDetails
和SiteLocation
,
因此,我将数据提取到UserDetails
并从用户“UserProject”添加到使用中NSPredicate
创建,这工作正常。我得到了所有项目的列表。SiteLocations
UITableView
fetchController
现在我想将 UserDetailspostcode
属性添加到SiteLocation
实体 - 对于 Attribute sitePostCode
,我可以Sitelocation
在地图上显示所有内容。
如何获取实体的第二个postcode
属性SiteLocation
?
@implementation SiteLocation (Create)
+(SiteLocation *)siteLocationWithName:(NSString *)sitename inManagedObjectContext:(NSManagedObjectContext *)context
{
SiteLocation *projectName = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SiteLocation"];
request.predicate = [NSPredicate predicateWithFormat:@"siteName = %@",sitename];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"siteName" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
NSArray *siteLocations = [context executeFetchRequest:request error:&error];
if (!siteLocations || ([siteLocations count] > 1)) {
// handle error
NSLog(@"site = 0");
} else if (![siteLocations count]) {
projectName = [NSEntityDescription insertNewObjectForEntityForName:@"SiteLocation"
inManagedObjectContext:context];
projectName.siteName = sitename;
//projectName.sitePostCode = sitePostCode;
} else {
projectName = [siteLocations lastObject];
}
NSLog(@"project name = %@", projectName);
return projectName;
}
创建UserDetails
代码
+(UserDetails*)userWithJsonInfo:(NSDictionary*)jsonInfo inManagedObjectContext:(NSManagedObjectContext *)context;
{
UserDetails *userdetail = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"UserDetails"];
request.predicate = [NSPredicate predicateWithFormat:@"userName = %@", [jsonInfo objectForKey:Employee_Name]]; // update Employee_Number
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"userName" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if (!matches || ([matches count] > 1)) {
//error handler
} else if ([matches count] == 0){
userdetail = [NSEntityDescription insertNewObjectForEntityForName:@"UserDetails" inManagedObjectContext:context];
userdetail.userID = [jsonInfo objectForKey:ID];
userdetail.userName = [jsonInfo objectForKey:Employee_Name];
userdetail.userEmail = [jsonInfo objectForKey:Email_Address];
userdetail.userMobile = [jsonInfo objectForKey:Phone_Handheld_No];
userdetail.userPhoto = [jsonInfo objectForKey:PhotoURL];
userdetail.postcode = [jsonInfo objectForKey:Project_Postcode];
userdetail.userProject = [jsonInfo objectForKey:Project_Description];
userdetail.projectUsers = [SiteLocation siteLocationWithName:[jsonInfo objectForKey:Project_Description]inManagedObjectContext:context];
//NSLog(@"user detail = %@", userdetail.userName);
} else {
userdetail = [matches lastObject];
}
return userdetail;
}