:道歉我对此我是全新的,我试图围绕核心数据。我有两个视图控制器。第一个(称为PVC)是一个表视图控制器,有两个部分,用于保存用户输入的名称和电子邮件。他们从该屏幕按下添加,然后将它们带到第二个视图控制器(称为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> ;
我只需要从该信息中获取name和settingsEmail键/值对。任何帮助将不胜感激!这是我的其余代码
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...\n\n\n"
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
答案 0 :(得分:0)
您的问题有点令人困惑,但您可以通过2种非常简单的方法从核心数据中获取特定信息。
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;
}];
如果这不是你问的那个,请告诉我,看看我是否可以提供帮助。