开发者

Pass An Object Between 2 View Controllers

开发者 https://www.devze.com 2023-03-29 22:42 出处:网络
I\'m trying to pass an object between 2 VCs, from a popover to the detail view of split view controller.

I'm trying to pass an object between 2 VCs, from a popover to the detail view of split view controller.

I think I need to use NSNotificationCenter.

I tried this but can't seem to get it to work.

In didSelectRow of popover

  [[NSNotificationCenter defaultCenter] postNotificationName:@"PassObject" withObject:objectToPass];

In detail VC

    - (void) didReceiveNotificationPassObject:(NSNotification*)notification  
    {
        YourObjectClass *theObject = (YourObjectClass*)notification.object;
    }

    - (void)viewDidLoad 
    {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveNotificationPassObject:) name:@"PassObject" o开发者_StackOverflowbject:nil];
    }


Probably just a typo when entering the question but in the first line where you post the notification

[[NSNotificationCenter defaultCenter] postNotificationName:@"PassObject" withObject:objectToPass];

the method signature is wrong - it should be 'object:objectToPass' not 'withObject:objectToPass'. The line you have there will compile with a warning and crash at runtime.

Aside from that all the logic seems fine.


What is the problem you are facing? Does didReceiveNotificationPassObject: hit? If it doesn't, you could verify that viewDidLoad executes before didSelectRow.

Use [[NSNotificationCenter defaultCenter] postNotificationName:@"PassObject" object:objectToPass]; instead of [[NSNotificationCenter defaultCenter] postNotificationName:@"PassObject" withObject:objectToPass];

Also, don't forget to removeObserver in viewDidUnload.

HTH,

Akshay


A fast and easy solution to notify with multiple parameters is to call the notification it like this

[[NSNotificationCenter defaultCenter] postNotificationName:@"shareButton" object:@"camera"];

Where "camera" acts like your parameter. Then

- (void)shareButton:(id)sender
{
   NSString *kindOf = [sender object];

    if ([kindOf isEqualToString:@"camera"]) {
         // Your code goes here
    }
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号