Noticationにデータを一緒に渡す
/* 通知を送る*/
[[NSNotificationCenter defaultCenter] postNotificationName:@"Hello"
object:nil];
これにStringの変数を渡します
↓
/* 通知を送る*/
NSString *string = @"HelloText";
[[NSNotificationCenter defaultCenter] postNotificationName:@"Hello"
object:string];
次に受け取るメソッドに引数にNotificationを追加
↓
-(void)hello:(NSNotification*)notification
notificationの中身を確認するとこんな感じ
Noticationから渡されたデータを抜き出す
NSConcreteNotification 0x608000043360 {name = Hello; object = HelloText}
ここから添付されたobject情報を抜き出す
↓
NSString *keyword = [NSString stringWithFormat:@"%@", [notification valueForKey:@"object"]];
or
NSString *keyword = (NSString *)notification.object;
といった感じになる。
以下変更したソース
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *button;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/* 通知を「受け取る」処理の登録----------------*/
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(hello:)
name:@"Hello"
object:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
/* 通知を送るアクション-----------*/
- (IBAction)buttonTapped:(id)sender {
NSString *string = @"HelloText";
[[NSNotificationCenter defaultCenter] postNotificationName:@"Hello"
object:string];
}
/* 動かしたい処理----------------*/
-(void)hello:(NSNotification*)notification
{
NSString *text = (NSString *)notification.object;
NSLog(@"%@",text);
}
/* 登録した通知登録の削除----------------*/
- (void)deallo
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
ソースの変更は前回の記事から続いてやっています
前回の記事