问题描述
|
我知道如何在2个视图之间共享数据。但是,如果我想使用tabBarController共享数据,我会迷路。
这是我的IBAction移到我的tabBar。
-(IBAction)goToPage2:(id)sender
{
tabController.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:tabController animated:YES];
}
我需要在tabBar的第一个视图中的IBAction中共享Nsstring * dataStr。
firstView *first = [[firstView alloc] initWithNibName:@\"firstView\" bundle:nil];
first.dataStr = name.text;
[tabController presentModalViewController:first animated:YES];
此代码无效。
谢谢
解决方法
在您的应用程序委托中声明一个@property。而且,您可以从应用程序的任何位置访问您的应用程序委托。
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication ]delegate]
,我同意特伦特的建议。但是我建议您在这种情况下使用数据类。在Appdelegate中使用属性不是一个好习惯。为此,您应始终使用数据类。
您创建一个数据类,如下所示:
您需要创建一个Data类,您可以在其中设置变量或案例数组的属性(用于在UITableView中显示数据)。在数据类中实现一个类方法,该方法检查对象是否已实例化。如果没有,它将执行此操作。就像这样:
//DataClass.h
@interface DataClass : NSObject {
NSMutableArray *nameArray;
NSMutableArray *placeArray;
}
@property(nonatomic,retain)NSMutableArray *nameArray;
@property(nonatomic,retain)NSMutableArray *placeArray;
+(DataClass*)getInstance;
@end
//DataClass.m
@implementation DataClass
@synthesize nameArray;
@synthesize placeArray;
static DataClass *instance =nil;
+(DataClass *)getInstance
{
@synchronized(self)
{
if(instance==nil)
{
instance= [DataClass new];
}
}
return instance;
}
现在,在您的视图控制器中,您需要将该方法调用为:
DataClass *obj=[DataClass getInstance];
并使用数组。
这样,您可以分配数据而不会打扰AppDelegate,这是一个好习惯。
,我在博客上写了一篇有关此类问题的冗长教程:http://www.hollance.com/2011/04/making-your-classes-talk-to-each-other-part-1/
您需要找出一种干净的方法来让您的控制器相互通信。我的教程介绍了几种方法以及每种方法的优点和缺点。值得学习如何执行此操作,因为您将要编写的几乎所有应用程序都会出现此问题。