使用委托(delegate)在不同的窗口之间传递数据

使用委托(delegate)在不同的窗口之间传递数据

在IOS里两个UIView窗口之间传递参数方法有很多,比如

 1.使用SharedApplication,定义一个变量来传递.

 2.使用文件,或者NSUserdefault来传递

 3.通过一个单例的class来传递 

 4.通过Delegate来传递。

今天想在两个UIViewController之间共享一个object,最早以前用得办法是先在一个controller里创建对象,然后其他 controller通过UITabViewController的view array找到之前的那个controller. 类似于:

NSArray *array = [tab viewControllers];

objectNeeded = [[[array objectAtIndex:0] objecNeededt] retain];

这个办法显然不好。今天google一下,主要有两种更好地解决方案。

把需要共享的object放在AppDelegate类里面。比如需要在两个class里传递一个string:

在YourAppDelegate里创建一个UILabel的instance

在class 1里面:

YourAppDelegate *mainDelegate = (YourAppDelegate *)[[UIApplication sharedApplication]delegate];

mainDelegate.mystring = Label1.text;

在class 2里面:

YourAppDelegate *mainDelegate = (YourAppDelegate *)[[UIApplication sharedApplication]delegate];

label2.text = mainDelegate.mystring;

但是不知道为什么YourAppDelegate *mainDelegate = (YourAppDelegate *)[[UIApplication sharedApplication]delegate];这句话在我的xcode里面不能通过编译。不过这个方法很多人是不推荐的。

创建一个singleton class,代码如下:

@interface DataSingleton : NSObject{

    

    int dataOK;

    int rowSelected;

    NSMutableArray* dataResult;

    

};

@property(assign) int dataOK;

@property(assign) int rowSelected;

@property(nonatomic, retain) NSMutableArray* dataResult;

+ (DataSingleton *)singleton;

@end

#import "DataSingleton.h"

#import "labelclass.h"

@implementation DataSingleton

@synthesize dataOK;

@synthesize dataResult;

@synthesize rowSelected;

static DataSingleton * MyCommon_Singleton = nil;

+ (DataSingleton *)singleton

{

    

    @synchronized(self)

    {

        if  (MyCommon_Singleton  ==  nil)

        {

            [[self alloc] init];

            MyCommon_Singleton.dataOK = 0;

            MyCommon_Singleton.rowSelected = 0;

            MyCommon_Singleton.dataResult = [[NSMutableArray alloc] init];

        }

    }

    

    return  MyCommon_Singleton;

    

}

+  (id)allocWithZone:(NSZone  * )zone

{

    @synchronized(self)

    {

        if (MyCommon_Singleton  ==  nil)

        {

            MyCommon_Singleton  =  [super allocWithZone:zone];

            return  MyCommon_Singleton;

        }

    }

    

    return  nil;

}

+ (void) Destroy

{

    MyCommon_Singleton.dataOK = 0;

   // for(int i = 0;i < [MyCommon_Singleton.dataResult count]; i++)

    [MyCommon_Singleton release];

 }

@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值