あるクラスから別のクラスに NSString を渡し、その NSString を 2 番目のクラスの 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