Sos*_*ily 11 iphone xcode objective-c ios
我遇到了一个有趣的问题,我有主ViewController让我用navController调用他MainVC,我正在从他执行performSegueWithIdentifier到我的第二个ViewController让我们称他为SecVC.所以,当我试图做popViewControllerAnimated我想将一些数据从SecVC传递给MainVc ..我知道我可以用appDelegate Param或单人类来做,但我的问题是:我能用更优雅的解决方案做到吗?就像我使用prepareForSegue并使用本地参数..
谢谢...
Sal*_*iom 18
最好的方法是使用委托.
//SecVCDelegate.h
#import <Foundation/Foundation.h>
@protocol SecVSDelegate <NSObject>
@optional
- (void)secVCDidDismisWithData:(NSObject*)data;
@end
Run Code Online (Sandbox Code Playgroud)
//SecVC.h
#import <UIKit/UIKit.h>
#import "SecVSDelegate.h"
@interface SecVC : UIViewController
/** Returns the delegate */
@property (nonatomic, assign) id<SecVSDelegate> delegate;
@end
Run Code Online (Sandbox Code Playgroud)
//SecVC.M
...
- (void) dealloc
{
...
delegate = nil
...
}
Run Code Online (Sandbox Code Playgroud)
什么时候popViewControllerAnimated,就在它之后(或之前),你这样做
if(_delegate && [_delegate respondsToSelector:@selector(secVCDidDismisWithData:)])
{
[_delegate secVCDidDismisWithData:myDataObject];
}
Run Code Online (Sandbox Code Playgroud)
在MainVC中,您必须确保实现委托函数 //MainVC.m
- (void)secVCDidDismisWithData
{
//do whatever you want with the data
}
Run Code Online (Sandbox Code Playgroud)
要避免任何警告,您必须告诉MainVC类如下所示实现委托:
//MainVC.h
#import "SecVCDelegate.h"
...
@interface MainVC : UIViewController <SecVCDelegate>
...
secVCInstance.delegate = self;
[self.navigationController pushViewController:secVCInstance];
...
Run Code Online (Sandbox Code Playgroud)
小智 16
虽然我同意最好的选择是使用Delegate,但如果任何人正在寻找不同的东西,他可以使用NSNotificationCenter作为替代.
在MainVC的viewDidLoad中:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(recvData:)
name:@"SecVCPopped"
object:nil];
}
Run Code Online (Sandbox Code Playgroud)
相加法recvData在MainVC.m
- (void) recvData:(NSNotification *) notification
{
NSDictionary* userInfo = notification.userInfo;
int messageTotal = [[userInfo objectForKey:@"total"] intValue];
NSLog (@"Successfully received data from notification! %i", messageTotal);
}
Run Code Online (Sandbox Code Playgroud)
现在在SecVC中,在弹出之前,添加此行
NSMutableDictionary* userInfo = [NSMutableDictionary dictionary];
[userInfo setObject:[NSNumber numberWithInt:messageTotal] forKey:@"total"];
NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"SecVCPopped" object:self userInfo:userInfo];
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12683 次 |
最近记录: |