7

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

//class1.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property(strong,nonatomic)NSString *variableString;

@end

//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

#import <UIKit/UIKit.h>

@interface ViewController2 : UIViewController

@property(strong,nonatomic)NSMutableArray *arr;

@end

//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
4

2 回答 2

39

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

[[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”?

于 2012-04-22T21:11:25.113 回答
0
Send your Notification like this:

        if(isComingFromHowToUseThisApp) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"noteFromVideoPlayer"
                                                            object:@"fromHowToUseThisApp"];
    }else {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"noteFromVideoPlayer"
                                                            object:@"fromVideoPlayerViewiPad"];
    }

Receive your notification like this:

// Reset the default value of table view in master split view
- (void)defaultCellSelectionOfTableView:(NSNotification *) objNotification {


     // We need to change the default selection of row
    NSString *noticeFromVideoPlayer = [objNotification object];

}// end defaultCellSelectionOfTableView
于 2013-12-04T11:52:06.557 回答