ios-单例和通知传值

1.通知传值

通知传值,是一种全局的传值手段, 能够在不同控制器,不同界面传值。

具体示例代码:

NSString *c1id = [NSString stringWithFormat:@"%@",thirtytagArr[indexPath.section][@"c1id"]];

     NSString *c2id = [NSString stringWithFormat:@"%@",thirtytagArr[indexPath.section][@"c2id"]];

    NSString *tapstr = [NSString stringWithFormat:@"%@",thirtytagArr[indexPath.section][@"taps"]];

    NSArray *taparr = [tapstr componentsSeparatedByString:@","];

    NSString *taps = [NSString stringWithFormat:@"%@,%@,%@",self.c2name,thirtytagArr[indexPath.section][@"name"],taparr[indexPath.row]];

     NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:c1id,@"c1id",c2id,@"c2id",taps,@"taps", nil];

    //创建通知

    NSNotification *notification =[NSNotification notificationWithName:@"tongzhi" object:nil userInfo:dict];

    //通过通知中心发送通知

    [[NSNotificationCenter defaultCenter] postNotification:notification];

    AddGoodViewController* oneVC =nil;

    

    for(UIViewController* VC in self.navigationController.viewControllers){

        

        if([VC isKindOfClass:[AddGoodViewController class]]){

            

            oneVC =(AddGoodViewController *) VC;

        [self.navigationController popToViewController:oneVC animated:YES];

        }

    }

然后在想传值到的界面的viewdidload里面注册通知,在dealloc里面移除监视通知:

- (void)viewDidLoad {

 //注册通知

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tongzhi:) name:@"tongzhi" object:nil];

}

- (void)dealloc{

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"tongzhi" object:nil];

}

2.单例的安全写法:

static  MySingleton  *shareSingleton = nil;

+( instancetype ) sharedSingleton  {

   static  dispatch_once  onceToken;

   dispatch_once ( &onceToken, ^ {

   shareSingleton  =  [[super allocWithZone:NULL] init] ;

} );

    return sharedSingleton;

}

+(id) allocWithZone:(struct _NSZone *)zone {

   return [Singleton shareInstance] ; 

}

-(id) copyWithZone:(struct _NSZone *)zone {

   return [Singleton shareInstance] ;

}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值