NSNotificationCenter用法实例

有时候需要两个界面传递值,以前用过protocol方法传过,不过不是很实用。
NSNotificationCenter很适合在两个界面传递。
下面把我写的方法粘贴上来

接受信息的类 accept.m-
static accept *m_instance;

+(accept *)getInstance{
   
    return m_instance;
}

- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization.
        m_instance=self;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addEventListeners];
   
}
-(void) addEventListeners
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(dealReceiveEvent:)
                                                 name:notificationName
                                               object:self];   
}

-(void) removeEventListeners
{

 [[NSNotificationCenter defaultCenter] removeObserver:self name:notificationName object:self];

}

- (void)dealloc {
    [super dealloc];
    [self removeEventListeners];
}

发送信息的类sender.m
可以直接调用doBack方法。
我这里传了一个CGPoint参数。
- (void) doBack:(CGPoint)offset
{
   
    if (m_curSelectedItem != -1) {
    NSString *curselected=[[NSString alloc] initWithFormat:@"%d",m_curSelectedItem];
    NSString *m_offset=[[NSString alloc] initWithFormat:@"%f",offset.x];
       
    NSMutableDictionary *dic= [[NSMutableDictionary alloc] init];
    [dic setObject:curselected forKey:@"1"];
    [dic setObject:m_offset forKey:@"2"];
   
    [[NSNotificationCenter defaultCenter] postNotificationName:notificationName
                                                        object:[accept getInstance]
                                                          userInfo:dic];   
    [curselected release];
    [m_offset release];
    [dic release];
    }
}

我把信息封装在NSDictionary里面发送的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值