使用NSNotification将NSString变量传递给其他类 [英] pass NSString variable to other class with NSNotification

查看:109
本文介绍了使用NSNotification将NSString变量传递给其他类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将NSString从一个类传递到另一个类,并将NSString添加到我的第二个类中的NSMutableArray。我相信我可以使用NSNotification,但我不知道如何通过变量通知。我的代码是这样的:

I want to pass a NSString from one class to another class and add that NSString to an NSMutableArray in my second class. I'm believe i can use NSNotification for this, but i don't know how to pass an variable over notification. My code would something like this:

// class1.h

//class1.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property(strong,nonatomic)NSString *variableString;

@end

// class1.m

//class1.m

#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

// class2.h

//class2.h

#import <UIKit/UIKit.h>

@interface ViewController2 : UIViewController

@property(strong,nonatomic)NSMutableArray *arr;

@end

// class2.m

//class2.m

#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


推荐答案

在发件人类中,您可以使用如下内容的对象发布通知:

In sender class you can post a notification with an object with something like this:

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

听众或接收者类必须注册通知:

The listener or receiver class has to register for the notification:

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

方法incomingNotification为:

The method incomingNotification is:

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



编辑



当您从ViewController发布通知时,是否加载了ViewController2?

EDIT

When you post the notification from "ViewController", is "ViewController2" loaded?

这篇关于使用NSNotification将NSString变量传递给其他类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆