从核心数据中提取某些键/值对会得到结果



:D抱歉,我对此一无所知,我正试图了解核心数据。我有两个视图控制器。第一个(称为PVC)是一个表视图控制器,有两个部分,用于保存用户输入的姓名和电子邮件。他们从屏幕上按add,然后进入第二个视图控制器(称为PDVC),用户在其中添加姓名和电子邮件,并指定条目将属于哪个部分(受托人或收件人)。当他们在屏幕上完成时,信息会被保存到核心数据中,并将其带回PVC,核心数据会在那里获取信息并将其放入表视图。

我试图实现的是,当用户点击PVC发送时,我需要获取该信息,(输入的每个名称和电子邮件)JSON,并将其发送到服务器。我用我想出的一个破解方法成功地做到了这一点,该方法将每个项存储到字典中,然后获取这些键/值对,并将它们添加到一个可变数组中,所有这些都来自PDVC。问题是,所有这些数据都需要像核心数据一样持久,所以使用核心数据来获取这些信息而不是我的破解是有意义的。我的问题是,这可能吗?我需要能够从核心数据中"提取"某些键值对。如果我能做到这一点,我相信我能解决剩下的问题。我知道有一种方法可以用来将核心数据信息存储到数组中,但它也附带了其他我不能使用的信息:

array of fetched objects: (
"<Credentials: 0xb9c6ed0> (entity: Credentials; id: 0xb9bfa90 <x-coredata://BE51A026-9D1B-      4A93-BA34-4EAC55B8B9DF/Credentials/p1> ; data: {n    category = Trustees;n    name = aef;n     settingsEmail = "inawef@hioe.com";n})",
"<Credentials: 0xb9c6f40> (entity: Credentials; id: 0xb9c6ae0 <x-coredata://BE51A026-9D1B- 4A93-BA34-4EAC55B8B9DF/Credentials/p3> ; data: {n    category = Trustees;n    name = awef;n     settingsEmail = "waef@aioc.com";n})",
"<Credentials: 0xb9c6fc0> (entity: Credentials; id: 0xb9c6af0 <x-coredata://BE51A026-9D1B- 4A93-BA34-4EAC55B8B9DF/Credentials/p2> ; 

我只需要从这些信息中得到名称和设置电子邮件密钥/值对。如有任何帮助,我们将不胜感激!这是我的代码的其余部分

PVC.h

@interface PeopleViewController : UITableViewController<NSFetchedResultsControllerDelegate>
{
NSMutableArray *listOfItems;
}
- (IBAction)doneButtonPressed:(id)sender;
- (IBAction)sendPressed:(id)sender;
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
@end

PVC.m

#import "PeopleViewController.h"
#import "AppDelegate.h"
#import "PeopleDetailViewController.h"
#import "Credentials.h"
#import "AlertLoad.h"
#import "Data.h"
#import "ASIFormDataRequest.h"

@interface PeopleViewController ()
@end
@implementation PeopleViewController
{
NSFetchedResultsController *fetchedResultsController;
AlertLoad *alertLoad;
Data *dataObj;
}
@synthesize managedObjectContext;

- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController == nil)
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription        entityForName:@"Credentials" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor1 = [NSSortDescriptor   sortDescriptorWithKey:@"category" ascending:NO];
NSSortDescriptor *sortDescriptor2 = [NSSortDescriptor  sortDescriptorWithKey:@"name" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor1,  sortDescriptor2, nil]];
[fetchRequest setFetchBatchSize:20];
fetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:@"category"
cacheName:@"Credentials"];
fetchedResultsController.delegate = self;
}
return fetchedResultsController;
}
- (void)performFetch
{
NSError *error;
if (![self.fetchedResultsController performFetch:&error]) {
FATAL_CORE_DATA_ERROR(error);
return;
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"view did load");
dataObj = [Data dataObj];
dataObj.trusteeArray = [[NSMutableArray alloc]init];
dataObj.recipientArray = [[NSMutableArray alloc]init];
if (self.managedObjectContext == nil)
{
self.managedObjectContext = [(AppDelegate *) [[UIApplication sharedApplication]  delegate] managedObjectContext];
NSLog(@"After managedObjectContext: %@",  self.managedObjectContext);
}
[self performFetch];
NSLog(@"array of fetched objects: %@", [fetchedResultsController fetchedObjects]);
[self.navigationController setToolbarHidden:NO];

self.navigationItem.title = @"Swipe to delete";
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
PeopleDetailViewController *controller = segue.destinationViewController;
controller.managedObjectContext = self.managedObjectContext;

}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//return [listOfItems count];
return [[self.fetchedResultsController sections] count];
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections]   objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:  (NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController  sections] objectAtIndex:section];
return [sectionInfo name];
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
Credentials *credentials = [self.fetchedResultsController objectAtIndexPath:indexPath];
if ([credentials.name length] > 0)
{
cell.textLabel.text = credentials.name;
}
else
{
cell.textLabel.text = @"(New Entry)";
}
if (credentials.settingsEmail != nil)
{
cell.detailTextLabel.text = credentials.settingsEmail;
}
else
{
cell.detailTextLabel.text = @"Tap to edit";
}
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:   (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
Credentials *credentials = [self.fetchedResultsController  objectAtIndexPath:indexPath];
[self.managedObjectContext deleteObject:credentials];
NSError *error;
if (![self.managedObjectContext save:&error]) {
FATAL_CORE_DATA_ERROR(error);
return;
}
}
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
}
[self configureCell:cell atIndexPath:indexPath];
// Set up the cell...
return cell;
}

-(void)infoSent
{
[alertLoad close];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Your trustees and recipients have been submitted" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)sendDataWithString:(NSString *)string
{
NSURL *url = [NSURL URLWithString:@"http://lastwords.com.au/lastwords/"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:dataObj.username              forKey:@"author"];
[request setPostValue:dataObj.password              forKey:@"password"];
[request setPostValue:string                        forKey:@"participants"];
[request setPostValue:@"set_participants"           forKey:@"json"];
[request startSynchronous];
NSError *error = [request error];
if (error != nil)
{
[alertLoad close];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
NSLog(@"error: %@", error);
}
else
{
NSString *response = [request responseString];
NSLog(@"response: %@", response);
[self performSelectorOnMainThread:@selector(infoSent) withObject:nil waitUntilDone:YES];
}
}
- (IBAction)doneButtonPressed:(id)sender
{
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)sendPressed:(id)sender
{
if ([self.tableView numberOfRowsInSection:0] > 3)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Too many trustees" message:@"You can only submit a maximum of 3 trustees." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
}
else if ([self.tableView numberOfRowsInSection:0] < 3)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Not enough trustees"  message:@"You must select 3 trustees." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
}
else if ([self.tableView numberOfSections] < 2)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No trustees or recipients" message:@"You must enter at least enter 3 trustees and at least one recipient." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
}
else
{
alertLoad = [[AlertLoad alloc]
initWithTitle:@"Submitting..."
message:@"Submitting your trustees and recipients. Please wait...nnn"
delegate:self cancelButtonTitle:@"Cancel"
otherButtonTitles:nil];
alertLoad.delegate = self;
[alertLoad show];
NSDictionary *dictionary = [NSDictionary  dictionaryWithObjectsAndKeys:dataObj.trusteeArray,@"trustees", dataObj.recipientArray,  @"recipients", nil];
NSError *error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:kNilOptions error:&error];
NSString* jSONString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"json??: %@", jSONString);
[self performSelectorInBackground:@selector(sendDataWithString:) withObject:jSONString];

}
}

@end

(取出提取结果委托的东西以节省空间)

PDVC.h

@interface PeopleDetailViewController : UIViewController<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *txtFieldName;
@property (weak, nonatomic) IBOutlet UITextField *txtFieldEmail;
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segment;
- (IBAction)done:(id)sender;
@end

PDVC.m

#import "PeopleDetailViewController.h"
#import "AppDelegate.h"
#import "Credentials.h"
#import "Data.h"
@interface PeopleDetailViewController ()
{
Data *dataObj;
}
@end
@implementation PeopleDetailViewController
@synthesize managedObjectContext;

- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"view did load");
dataObj = [Data dataObj];
if (self.managedObjectContext == nil)
{
self.managedObjectContext = [(AppDelegate *) [[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(@"After managedObjectContext: %@",  self.managedObjectContext);
}
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

#pragma mark - textField Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}

- (IBAction)done:(id)sender
{
NSString *emailRegEx = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
if (self.txtFieldEmail.text.length < 1 || self.txtFieldName.text.length < 1)
{
[self dismissViewControllerAnimated:YES completion:nil];
}
else if ([emailTest evaluateWithObject:self.txtFieldEmail.text] == NO)
{
//Valid email addres
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid email" message:@"Please enter a valid email address" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
}
else
{
Credentials *credentials = [NSEntityDescription insertNewObjectForEntityForName:@"Credentials" inManagedObjectContext:self.managedObjectContext];
credentials.name = self.txtFieldName.text;
credentials.settingsEmail = self.txtFieldEmail.text;
if (self.segment.selectedSegmentIndex == 0)
{
credentials.category = @"Trustees";
NSDictionary *trusteeDict = [NSDictionary dictionaryWithObjectsAndKeys:self.txtFieldName.text,@"name", self.txtFieldEmail.text,@"email", nil];
NSError *error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:trusteeDict options:kNilOptions error:&error];
NSString* jSONString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"json??: %@", jSONString);
[dataObj.trusteeArray addObject:trusteeDict];
NSLog(@"trusteeArray: %@", dataObj.trusteeArray);
}
else
{
credentials.category = @"Recipients";
NSDictionary *recipientDict = [NSDictionary dictionaryWithObjectsAndKeys:self.txtFieldName.text,@"name", self.txtFieldEmail.text,@"email", nil];
NSError *error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:recipientDict options:kNilOptions error:&error];
NSString* jSONString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"json??: %@", jSONString);
[dataObj.recipientArray addObject:recipientDict];
NSLog(@"recipientArray: %@", dataObj.recipientArray);
}
NSError *error;
if (![self.managedObjectContext save:&error])
{
FATAL_CORE_DATA_ERROR(error);
return;
}
[self dismissViewControllerAnimated:YES completion:nil];
}
}

@end

您的问题有点令人困惑,但您可以使用两种非常简单的方法从核心数据中获取特定信息。

1) 在提取中使用类似于以下的谓词

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"User"
inManagedObjectContext:self.managedObjectContext];
fetchRequest.entity = entity;
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"userID = %@", userIDYouAreLookingfor];
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
NSLog(@"%@",fetchedObjects);

2) 父关系的实体在NSSet中指定,您可以测试它们以检索某些对象:

NSSet *picturesResult = [_thumbnailsStorage.pictures objectsPassingTest:^BOOL(id obj, BOOL *stop) {
Picture *pic = obj;
// Check for a condition here
if (someCondition) {
return YES;
}
return NO;
}];

如果这不是你要求的,请告诉我,我会看看我是否能帮忙。

相关内容

最新更新