0

I am new to iOS.I am recently stuck with a problem. I have a view A and View B. View A has a navigation controller. view A has a button to switch to B.When i am clicking this button every time B creates a new object. how can i track this object to share data between this two view. Thanks

Tunvir Rahman Tusher
  • 6,421
  • 2
  • 37
  • 32

2 Answers2

2

There are several ways to do this.

You could have a property of B, that A sets before you push. (NSDictionary, Array, String etc) This not the best way however it would work.

UIViewController *viewB = [[UIViewController alloc]init];
[viewB setMyProperty:@"some data!"];
[self.navigationController pushViewController:viewB animated:YES];

You could also use NSNotificationCenter to pass the object to the next view.

NSDictionary *dictionary = [NSDictionary dictionaryWithObject:
                         [NSNumber numberWithInt:index]
                      forKey:@"index"];

[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification"
                                      object:self
                                      userInfo:dictionary];

The way I usually handle this is to setup and object that holds my data with an associated protocol initialized in my AppDelegate. Then any view that needs to read/write something just grabs a Pointer to that object and runs with it.

@class AppData;

@protocol AppDataProtocol

- (AppData*)theAppData;

@end 

in the View you can grab the pointer with this.

-(AppData*)theAppData {

    id<AppDataProtocol> theDelegate = (id<AppDataProtocol>)[UIApplication sharedApplication].delegate;
    AppData* theData = (AppData*)theDelegate.theAppData;

    return theData;
}

and this.

 appData = [self theAppData];

You are then able to easily access any property of appData.

Kenrik March
  • 369
  • 1
  • 5
0
-(void)fnButtonA{

ViewB *vcB = [[ViewB alloc] initWithData:DataToB];
[[self navigationController] pushViewController:vcB animated:Yes];

}


In ViewB.m edit the init function to 

-(UIViewController *)initWithData:(NSMutableDictionary*)data
Mohith
  • 96
  • 5