Я просмотрел некоторые учебники и даже посмотрел видеоролик Apple WWDC 2011 о том, как создать собственный протокол для отправки данных назад, и кажется, что я чего-то не хватает, но я не могу точно определить, что именно. У меня есть контроллер представления addUrination, который выталкивается в стек из диаграмм контроллера. Я создал протокол и свойство delegate в addUrination.h, чтобы попытаться отправить сообщение в диаграммы при отправке данных. Когда отправляется ввод данных, я вызываю сообщение, которое я создал в своем пользовательском протоколе, и реализовал его в Charts.m, но сообщение никогда не отправляется, поскольку мой вызов NSLog никогда не появляется в консоли. Я вспомнил, что должен был установить делегата при подготовке к segue из Charts.m. Спасибо за любую информацию, потому что понимание того, что не так с этим, очень поможет в обучении отправке сообщений назад.Пользовательские протоколы, не отправляющие сообщения
AddUrination.h
#import <UIKit/UIKit.h>
@class AddUrination;
@protocol AddUrinationDelegate <NSObject>
- (void)addUrinationViewController:(AddUrination *)controller didFinishEnteringUrination:(NSNumber *)urination;
@end
@interface AddUrination : UITableViewController<UITextFieldDelegate>
@property (weak,nonatomic) id<AddUrinationDelegate> delegate;
@end
AddUrination.m
-(IBAction)addUrination:(id)sender
{
PFObject *amount=[PFObject objectWithClassName:@"urinationAmount"];
NSNumberFormatter *number=[[NSNumberFormatter alloc]init];
[number setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *urinateAmount=[number numberFromString:self.addUrinationTextField.text];
/*Create activity indicator*/
UIActivityIndicatorView *spinner=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[spinner setCenter:CGPointMake(self.tableView.frame.size.width/2.0,(self.tableView.frame.size.height-self.keyboardHeight)/2.0)];
spinner.layer.backgroundColor=[[UIColor blackColor]CGColor];
spinner.layer.cornerRadius=10;
[self.view addSubview:spinner];
[spinner startAnimating];
if(urinateAmount!=nil){
[amount setObject:urinateAmount forKey:@"amountOfUrine"];
PFUser *user=[PFUser currentUser];
[amount setObject:user forKey:@"user"];
[amount saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if(!error) {
[spinner stopAnimating];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Thank You!" message:@"Your urination amount has been successfully saved" delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil];
[alert show];
UrinationData *dataSettings=[UrinationData sharedUrinationData];
[dataSettings setUrinationDataChanged:YES];
[email protected]"";
[self.delegate addUrinationViewController:self didFinishEnteringUrination:urinateAmount];
[self.navigationController popViewControllerAnimated:YES];
}
else{
[spinner stopAnimating];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Uh-oh!" message:@"There was an error on our end. Please try again!" delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil];
[alert show];
}
}];
}
else{
[spinner stopAnimating];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Uh-oh!" message:@"Please enter a valid amount" delegate:nil cancelButtonTitle:@"Sorry" otherButtonTitles:nil, nil];
[alert show];
}
}
Charts.h
#import <UIKit/UIKit.h>
#import "CorePlot-CocoaTouch.h"
#import "CPTAnimation.h"
#import "AddUrination.h"
@interface Charts : UIViewController<CPTPlotDataSource,CPTPlotSpaceDelegate,CPTScatterPlotDelegate,CPTScatterPlotDataSource,CPTAnimationDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate,AddUrinationDelegate>
@property(nonatomic,strong)CPTXYPlotSpace *plotSpace;
@property(nonatomic,strong)CPTXYGraph *graph;
@property(nonatomic,strong)CPTGraphHostingView *hostingView;
@property(nonatomic,strong)NSString *graphTitle;
@property(nonatomic,strong)UISegmentedControl *chartsSegmentedControl;
@property(nonatomic,strong)CPTPlotSpaceAnnotation *urinationAnnotation;
@end
Charts.m
-(void)addUrinationViewController:(AddUrination *)controller didFinishEnteringUrination:(NSNumber *)urination{
NSLog(@"Urination was entered from add urination screen");
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if([segue.identifier isEqualToString:@"AddUrinationSegue"]){
AddUrination *addUrination=[segue destinationViewController];
addUrination.delegate=self;
}
}
Да, это было так. Charts.m - это страницы контроллера страницы, поэтому segue фактически вызывается из контейнера контроллера View, содержащего контроллер просмотра страницы. Теперь я не могу добавить элемент в панель навигации для выполнения segue from charts.m –
Я попытался добавить кнопку в панель навигации, вызвав self.parentViewController.navigationItem.rightBarButton, но это не сработало. Гораздо полезнее отправить сообщение на страницы, а не в контейнер в моем сознании –
Пожалуйста, дайте более подробную информацию? или привязка кода. – Sandy