好的,所以這是我昨晚問的一個問題的擴展。我對使用各種技術在視圖控制器之間傳遞數據的方式有了更加清楚的認識。我想去MVC路線,創建一個Singleton類似乎是最接近MVC的概念。Obj-C - 如何使用單例在視圖控制器之間傳遞數據?
基本上我創建了一個簡單的應用程序與兩個視圖控制器和一個單例類。我正在嘗試將文本字段的值傳遞給UILabel。無論出於何種原因,它都不起作用。這是我的代碼看起來像。
ViewController.h
#import <UIKit/UIKit.h>
#import "Model.h"
#import "ViewController2.h"
@interface ViewController : UIViewController {
NSString *text2pass;
}
@property (weak, nonatomic) IBOutlet UITextField *tf;
@property (weak, nonatomic) IBOutlet UILabel *btn;
- (IBAction)go:(id)sender;
@end
ViewController.m
#import "ViewController.h"
@interface ViewController()
@end
@implementation ViewController
@synthesize tf = _tf;
@synthesize btn = _btn;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *tfstring = _tf.text;
NSLog(@"string = %@",tfstring);
}
- (void)viewDidUnload
{
[self setTf:nil];
[self setBtn:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (IBAction)go:(id)sender {
NSLog(@"btn pressed");
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
ViewController2 *vc2 = (ViewController2 *) [storyboard instantiateViewControllerWithIdentifier:@"home"];
text2pass = _tf.text;
[self passValues];
[self presentModalViewController:vc2 animated:YES];
}
-(void) passValues {
Model *model = [Model sharedModel];
model.passedText = text2pass;
}
@end
ViewController2.h
#import <UIKit/UIKit.h>
#import "ViewController.h"
@interface ViewController2 : UIViewController {
NSString *passedText;
}
@property (nonatomic)NSString *passedValue;
@property (weak, nonatomic) IBOutlet UILabel *lbl;
- (IBAction)back:(id)sender;
@end
ViewController2.m
#import "ViewController2.h"
@interface ViewController2() {
NSString *passedtext;
}
@end
@implementation ViewController2
@synthesize lbl = _lbl;
@synthesize passedValue = _passedValue;
- (void)viewDidLoad
{
// do code stuff here
NSLog(@"passedText = %@",passedText);
_lbl.text = passedText;
[super viewDidLoad];
}
- (void)viewDidUnload
{
[self setLbl:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (IBAction)back:(id)sender {
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
ViewController *vc = (ViewController *) [storyboard instantiateViewControllerWithIdentifier:@"welcome"];
[self presentModalViewController:vc animated:YES];
}
@end
Model.h
#import <Foundation/Foundation.h>
@interface Model : NSObject {
NSString *passedText;
}
@property (nonatomic, strong) NSString* passedText;
+ (Model *) sharedModel;
@end
Model.m
#import "Model.h"
@implementation Model
@synthesize passedText = _passedText;
static Model *sharedModel = nil;
+ (Model *) sharedModel {
@synchronized(self){
if (sharedModel == nil){
sharedModel = [[self alloc] init];
}
}
return sharedModel;
}
@end
該項目可將其全部從這裏http://chrisrjones.com/files/KegCop-Test.zip
下載如果您知道UILabel爲什麼不顯示文本字段文本,請告訴我。哦,我幾乎遵循了這個 - >http://www.youtube.com/watch?v=ZFGgMPcwYjg&feature=plcp