私は簡単なチュートリアルを行っており、NSNotification
それを適切に実行する上でいくつかの問題に直面しています。最初のビューのボタンをクリックしても、2番目のビューのテキストフィールドが更新されません。にを入れてデバッグするNSLog
とreceiveNotification
、応答がありません。receiveNotification
が呼び出されていない理由がわかりません。
コードは次のようになります。
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController{
}
-(IBAction)one:(id)sender;
-(IBAction)two:(id)sender;
-(IBAction)secondview:(id)sender;
@end
ViewController.m
#import "ViewController.h"
#import "SecondViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)one:(id)sender{
[[NSNotificationCenter defaultCenter] postNotificationName:@"Test1" object:self];
NSLog(@"Hello");
}
-(IBAction)two:(id)sender{
[[NSNotificationCenter defaultCenter] postNotificationName:@"Test2" object:self];
NSLog(@"Hello");
}
-(IBAction)secondview:(id)sender{
SecondViewController *secondview = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
[self presentViewController:secondview animated:YES completion:nil];
}
@end
SecondViewController.h
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController{
IBOutlet UITextField *counterOneText;
IBOutlet UITextField *counterTwoText;
int counterOne;
int counterTwo;
}
-(IBAction)back:(id)sender;
@end
SecondViewController.m
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
counterOne = 0;
counterTwo = 0;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification) name:@"Test1" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification) name:@"Test2" object:nil];
}
return self;
}
-(void)receiveNotification:(NSNotification *)notification{
if([[notification name] isEqualToString:@"Test1"]) {
counterOne++;
counterOneText.text = [NSString stringWithFormat:@"%d",counterOne];
NSLog(@"%@",counterOneText.text);
NSLog(@"Hello");
}else
{
counterTwo++;
counterTwoText.text = [NSString stringWithFormat:@"%d",counterTwo];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)back:(id)sender{
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
これに関するガイダンスが必要です。