方式一:透過定義一個實體類來傳值(從 ViewController1 跳轉至 ViewController2)。
.h 宣告檔:
#import <Foundation/Foundation.h>
@interface NotificationEntity : NSObject
{
}
@property (nonatomic,retain) NSString *strTitle; // 參數一
@property (nonatomic,retain) NSString *strContent; // 參數二
@property (nonatomic,retain) NSString *strUrl; // 參數三
@end
.m 實作檔:
#import "NotificationEntity.h" @implementation NotificationEntity @synthesize strTitle = _strTitle; @synthesize strContent = _strContent; @synthesize strUrl = _strUrl; @end
在 .h 中將 NotificationEntity 宣告為類成員變數:
@property (retain,nonatomic) NotificationEntity *mNotifEntity;
在 .m 中合成存取方法:
@synthesize mNotifEntity = _mNotifEntity;
// 組裝實體類的實例變量 NotificationEntity *mNotificationEntity = [[NotificationEntity alloc] init]; [mNotificationEntity setStrTitle:strTitle]; [mNotificationEntity setStrContent:strContent]; [mNotificationEntity setStrUrl:strUrl]; // 實例化 ViewController2 ViewController2 *viewController2 = [[ViewController2 alloc] init]; // 注入參數 [viewController2 setMNotifEntity:mNotificationEntity]; // 跳轉 [self.window.rootViewController presentModalViewController:viewController2 animated:YES];
- (void)viewDidLoad {
[super viewDidLoad];
[self.lblTitle setText:[self.mNotifEntity strTitle]];
[self.lblContent setText:[self.mNotifEntity strContent]];
}
- (IBAction)backOff:(id)sender {
[self dismissModalViewControllerAnimated:YES];
}
如此一來,透過實體類即可在兩個 ViewController 之間完成資料的傳遞與回傳。