передать переменную NSString в другой класс с помощью NSNotification

Я хочу передать NSString из одного класса в другой класс и добавить этот NSString в NSMutableArray во втором классе. Я считаю, что могу использовать NSNotification для этого, но я не знаю, как передать переменную через уведомление. Мой код будет примерно таким:

//класс1.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property(strong,nonatomic)NSString *variableString;

@end

//класс1.м

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize variableString = _variableString;

- (void)viewDidLoad
{
[super viewDidLoad];
[self setVariableString:@"test"];

[[NSNotificationCenter defaultCenter] postNotificationName: @"pasteString" object: _variableString];

// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}

@end

//класс2.ч

#import <UIKit/UIKit.h>

@interface ViewController2 : UIViewController

@property(strong,nonatomic)NSMutableArray *arr;

@end

//класс2.м

#import "ViewController2.h"

@interface ViewController2 ()

@end

@implementation ViewController2

@synthesize arr = _arr;


- (void)viewDidLoad:(BOOL)animated   
{
[super viewDidLoad];
if(_arr == nil)
{
    _arr = [[NSMutableArray alloc]init];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incomingNotification:) name:@"pasteString" object:nil]; 
// Do any additional setup after loading the view.
}

- (void) incomingNotification:(NSNotification *)notification{
NSString *theString = [notification object];
[_arr addObject:theString];
}

@end

person Niels Sønderbæk    schedule 22.04.2012    source источник


Ответы (1)


В классе отправителя вы можете опубликовать уведомление с объектом примерно так:

[[NSNotificationCenter defaultCenter] postNotificationName: NOTIFICATION_NAME object: myString];

Класс слушателя или получателя должен зарегистрироваться для получения уведомления:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(incomingNotification:) name:NOTIFICATION_NAME object:nil];

Метод incomingNotification:

- (void) incomingNotification:(NSNotification *)notification{
   NSString *theString = [notification object];
   ...
}

РЕДАКТИРОВАТЬ

Когда вы публикуете уведомление из «ViewController», загружается ли «ViewController2»?

person Jonathan Naguin    schedule 22.04.2012
comment
Я обновил свой код выше, но он у меня не работает. Вы видите что-то не так с кодом? - person Niels Sønderbæk; 23.04.2012
comment
Вызывается ли ViewController2? - person Jonathan Naguin; 23.04.2012
comment
Нет, я забыл перейти к viewcontroller2. Этот код работает сейчас. Большое Вам спасибо :) - person Niels Sønderbæk; 23.04.2012
comment
Он работает нормально. Но я хочу отправить значение из View Controller1 в View Controller2. В каком месте я вызываю уведомление о почте. - person vijay; 12.02.2015
comment
для новых людей (я), я считаю, также необходимо '[[NSNotificationCenter defaultCenter] removeObserver:self];' в методе viewWillDisappear или Dealloc в классе получателя/лизера. (спасибо, Джонатан) - person tmr; 08.04.2015