:Dお詫び申し上げます。私はこれにまったく慣れておらず、コアデータに頭を悩ませようとしています。私は2つのビューコントローラーを持っています。最初のもの(PVCと呼ばれる)は、ユーザーが入力する名前と電子メールを保持する2つのセクションを持つテーブルビューコントローラーです。その画面から[追加]を押すと、2番目のビューコントローラー(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> ;
その情報から、名前と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