我有一个多视图的应用程序。在视图上我创建了NSDate
如下:
NSString *storeDate = [[NSDate date] description];
在视图2上,viewDidLoad:
我想使用
storeDate
值
timeRecord.text = storeDate;
我已导入我的观点,但storeDate
被标记为未声明。
知道如何才能让它发挥作用吗?
SOFViewController.h
#import <UIKit/UIKit.h>
@interface SOFViewController : UIViewController {
}
-(IBAction) storeDateBut: (id) sender;
-(IBAction) goToView2: (id) sender;
@property (nonatomic,retain) NSString *storeDate;
@end
SOFViewController.m
#import "SOFViewController.h"
#import "view2.h"
@implementation SOFViewController
@synthesize storeDate;
-(IBAction) storeDateBut: (id) sender{
self.storeDate = [[NSDate date] description];
}
-(IBAction) goToView2: (id) sender{
view2 *myview2 = [[view2 alloc] initWithNibName:@"view2" bundle:nil];
[self.view addSubview:myview2.view];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
}
- (void)dealloc {
[super dealloc];
}
@end
view2.h
#import <UIKit/UIKit.h>
@interface view2 : UIViewController {
IBOutlet UILabel *dateLabel;
}
-(IBAction) goToView1: (id) sender;
@property (nonatomic, retain) IBOutlet UILabel *dateLabel;
@end
view2.m
#import "view2.h"
#import "SOFViewController.h"
@implementation view2
@synthesize dateLabel;
-(IBAction) goToView1: (id) sender{
SOFViewController *mySOFViewController = [[SOFViewController alloc] initWithNibName:@"view2" bundle:nil];
[self.view addSubview:mySOFViewController.view];
}
- (void)viewDidLoad {
dateLabel.text = SOFViewController.storeDate;
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[super dealloc];
}
@end
答案 0 :(得分:1)
storeDate的范围仅限于view1的方法。因此,您无法访问其他视图甚至同一类的其他方法。你必须制作“storeDate”属性,然后你可以在任何地方访问它,如
@interface view1:UIView {}
@property(nonatomic, retain) NSString *storeDate;
@end
在实施中使用
@synthesize storeDate;
现在将storeDate的值设置为
self.storeDate = [[NSDate date] description];
你可以在任何地方使用它。
答案 1 :(得分:0)
我从您的问题中假设您的意思是您的应用中有多个视图控制器。
storeDate
只是您声明的方法的本地化。我认为您需要阅读variable scope in Objective-c
答案 2 :(得分:0)
使用此代码。
在视图2中。
#import "view2.h"
#import "SOFViewController.h"
@implementation view2
@synthesize dateLabel;
-(IBAction) goToView1: (id) sender{
SOFViewController *mySOFViewController = [[SOFViewController alloc] initWithNibName:@"view2" bundle:nil];
[self.view addSubview:mySOFViewController.view];
}
- (void)viewDidLoad {
dateLabel.text = mySOFViewController.storeDate;
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[super dealloc];
}
@end