我知道如何处理2个视图之间的共享数据。但是,如果我想使用tabBarController共享数据,我就迷失了。
这是我移动到tabBar的IBAction。
-(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];
此代码不起作用。
THX
答案 0 :(得分:3)
在您的app委托中声明@property。您可以从应用的任何位置访问您的应用代理。
MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication ]delegate]
答案 1 :(得分:3)
我同意特伦特的建议。但我建议你在这种情况下应该使用数据类。在Appdelegate中使用属性不是一个好习惯。您应该始终使用数据类。
您可以按如下方式创建Data类:
您需要创建一个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的情况下分配数据,这是一种很好的做法。
答案 2 :(得分:0)
我在博客上写了一篇关于此类问题的冗长教程:http://www.hollance.com/2011/04/making-your-classes-talk-to-each-other-part-1/
您需要找到一种干净的方式让您的控制器相互通信。我的教程解释了几种方法,以及每种方法的优点和缺点。值得学习如何做到这一点,因为这个问题几乎出现在你要编写的任何应用程序中。