I've spent a few hours on this trying to work it out myself but I give up!
I have a master-detail arrangement where the user input screen needs to call a function on another class to post to a web service. Upon completion of the asynchronous call, the class will then call a specified function. In this case, I'm just testing and all I want to do is go back to the main screen after the user input is accepted by the web service.
When the uses taps a button on the input screen (SetLocationViewController), the asynchronous operation is called in the class APIPostClass. After it is complete, I want SetLocationViewController to segue back to MasterViewController.
In APIPostClass.m in (called after the asynchronous op finishes)
-(void)callWhenDone {
NSLog(#"callWhenDone loaded.");
SetLocationViewController *SLVClassInstance = [[SetLocationViewController alloc] init];
[SLVClassInstance doSegue];
}
In SetLocationViewController.m
-(void) doSegue {
NSLog(#"doSegue loaded");
[self performSegueWithIdentifier:#"SetLocationViewControllerManualUnwind" sender:self];
}
Calling doSegue from an action on SetLocationViewController.m does work so I know my segue is ok but the above doesn't work. I get the error reason: 'Receiver () has no segue with identifier 'SetLocationViewControllerManualUnwind''
I'm guessing the reason is because of the alloc init way of initialising of the VC, but I don't know any better. Thus, how can I call a function on another class as if it was being called by it's own class?
Create a delegate it would be much more reliable and fast than Notifications.
#protocol APIPostDelegate <NSObject>
#required
-(void)OnRequestSucess;
#end
In your APIPost add new property for delegate
#interface APIPost : NSObject
#property (weak) id<APIPostDelegate> delegate;
In SetLocationViewController implement APIPostDelegate
SetLocationViewController.h
SetLocationViewController :NSObject<APIPostDelegate>
SetLocationViewController.m
-(void)OnRequestSucess
{
[self doSegue];
}
before you make call to method on APIPost, assign self to delegate property.
APIPost *apipost=[[APIPost alloc]init];
apipost.delegate=self;
[apipost <your api method>];
APIPost.m
[self.delegate OnRequestSucess];
Hope this helps.
There are a few methods to make it happens:-
Use Delegate
Use NSNotification.
The way described by Artur above (For SplitViewController Only - iPad)
You should use delegate whenever it is possible but it might not be too straight forward. NSNotification is more straight forward but it is not a good practice and not a good programming style.
I will only share the NSNotification method as it is easier to implement.
In SetLocationViewController.m
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(doSegue) name:#"calldoSegue" object:nil];
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter]removeObserver:self name:#"calldoSegue" object:nil];
}
-(void) doSegue {
NSLog(#"doSegue loaded");
[self performSegueWithIdentifier:#"SetLocationViewControllerManualUnwind" sender:self];
}
In APIPostClass.m
-(void)callWhenDone {
NSLog(#"callWhenDone loaded.");
[[NSNotificationCenter defaultCenter]postNotificationName:#"calldoSegue" object:nil];
}
The above code should work but again, this is not a good practice. You should try to learn the Delegate method.
The answer is here: Performing segue from another class
In my APIPostClass.h, I setup the view controller:
#interface APIPostClass : NSObject {
SetLocationViewController *setLocationViewController;
}
#property(nonatomic, strong) SetLocationViewController *setLocationViewController;
#end
In my APIPostClass.m, I synthesize it:
#synthesize setLocationViewController;
then, instead of this (as in my question):
-(void)callWhenDone {
NSLog(#"callWhenDone loaded.");
SetLocationViewController *SLVClassInstance = [[SetLocationViewController alloc] init];
[SLVClassInstance doSegue];
}
I have:
-(void)callWhenDone {
NSLog(#"callWhenDone loaded");
[self.setLocationViewController doSegue];
}
Over in SetLocationViewController.m, the segue method remains unchanged:
-(void) doSegue {
NSLog(#"doSegue loaded");
[self performSegueWithIdentifier:#"SetLocationViewControllerManualUnwind" sender:self];
}
But when I call my API, I need to "attach" (forgive my terminology) the view controller to it. This is what I had:
- (IBAction)btnTestAPICall:(id)sender {
NSLog(#"User tapped API button");
APIPostClass *APIPostClassInstance = [[APIPostClass alloc] init];
[APIPostClassInstance APICall: ... ....
}
But this is what works after bringing all of the above:
- (IBAction)btnTestAPICall:(id)sender {
NSLog(#"User tapped API button");
APIPostClass *APIPostClassInstance= [[APIPostClass alloc] init];
UIViewController *currentVC=self;
APIPostClassInstance.setLocationViewController = currentVC;
[APIPostClassInstance APICall: ... ...
I hope this will help someone else!
Related
Hi im developing an app that has a parent view that then used containers to embed other views as seen below.
For now im only working with the left and centre container which are both table views. The main view or the Project screen view is my parent controller and i want it to pass data to and from the two child controller and i know for this the best option is to use delegates. However each example i have looked at that uses delegates, created and initialises a new view controller so for example lets say the left container embeds a view using the leftviewcontroller. Each example has this line of code.
LeftViewController *sampleProtocol = [[LeftViewController alloc]init];
LeftViewController.delegate = self;
Im thinking i dont need to create a new LeftViewController since it is embeded it is already in my list of child controllers. So my queston is how would i get the controller from the list of child controllers and set the parent as the delegate. I know i it is an array and i can use objectAtIndex but how do i know the order of items in the array will not change can i not call it but a tag or identifier? Thank you for any help sorry if the question is not that clear its my first time setting up delegates.
i know for this the best option is to use delegates.
In this case, I wouldn't be so sure. I think the best option would be to have a robust model and use KVO and notifications to signal updates between view controllers.
The direct answer to your question is not too bad.
for (UIViewController *viewController in self.childViewControllers) {
if ([viewController isKindOfClass:[LeftViewController class]]) {
LeftViewController *leftViewController = (id)viewController;
leftViewController.delegate = self;
break;
}
}
I think a minor improvement on this would be to use the segue. Make sure each of the containers have a named segue. In this example, the left view controller has a segue with the identifier "Load Child LeftViewController".
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"Load Child LeftViewController"]) {
LeftViewController *leftViewController = segue.destinationViewController;
leftViewController.delefate = self;
}
}
Its always better to use NSNotificationCenter for such complex mechanism.
*** put following code in LeftController.m ***
// *** Register a Notification to recieve a Data when something happens in Center controller ***
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receivedNotification:)
name:#"hasSomeData"
object:nil];
// *** create a method to receive Notification data ***
- (void)receivedNotification:(NSNotification *) notification {
if ([[notification name] isEqualToString:#"hasSomeData"])
{
// do your stuff here with data
NSLog(#"data %#",[notification object]);
}
}
*** when something happen in center controller post a notification to inform Left Controller ***
[[NSNotificationCenter defaultCenter] postNotificationName:#"hasSomeData" object:self];
//Secondvc.h
#protocol Sendmessage<NSObject>
#required
-(void)Object:(NSArray *)tosend;
#end
#interface Secondvc:UIViewcontroller{
id <Sendmessage> delegate;
}
#property(strong,nonatomic) id <Sendmessage> delegate;
#end
//Secondvc.m
#implementation Secondvc
#synthesize delegate;
-(void)viewDidLoad{
//Do Something here!
}
//Pass Some Value When a button event occured in Second vc
-(IBAction)Send_Data{
[self dismissViewControllerAnimated:Yes completion:nil];
[self.delegate Object:[NSArray Arraywithobjects:#"Hello",nil]];
}
#end
//FirstVc.h
#import "Secondvc.h"
#interface FirstVc<Sendmessage>
#end
//FirstVc.m
#implementation FirstVc
-(void)viewDidLoad{
Secondvc* Object=[[Secondvc alloc]init];
Object.delegate=self;
}
#pragma mark Secondvc Deklegate method implementation
-(void)Object:(NSArray *)tosend{
NSLog(#"Recieved data Form Second VC Is:\n%#",tosend);
}
#end
HTH!Enjoy Coding.
I want to check the pasteboard and show an alert if it contains specific values when the view appears. I can place the code into viewDidLoad to ensure it's only invoked once, but the problem is that the alert view shows too quickly. I know I can set a timer to defer the alert's appearance, but it's not a good work-around I think.
I checked the question iOS 7 - Difference between viewDidLoad and viewDidAppear and found that there is one step for checking whether the view exists. So I wonder if there's any api for doing this?
Update: The "only once" means the lifetime of the view controller instance.
There is a standard, built-in method you can use for this.
Objective-C:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if ([self isBeingPresented] || [self isMovingToParentViewController]) {
// Perform an action that will only be done once
}
}
Swift 3:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if self.isBeingPresented || self.isMovingToParentViewController {
// Perform an action that will only be done once
}
}
The call to isBeingPresented is true when a view controller is first being shown as a result of being shown modally. isMovingToParentViewController is true when a view controller is first being pushed onto the navigation stack. One of the two will be true the first time the view controller appears.
No need to deal with BOOL ivars or any other trick to track the first call.
rmaddy's answers is really good but it does not solve the problem when the view controller is the root view controller of a navigation controller and all other containers that do not pass these flags to its child view controller.
So such situations i find best to use a flag and consume it later on.
#interface SomeViewController()
{
BOOL isfirstAppeareanceExecutionDone;
}
#end
#implementation SomeViewController
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if(isfirstAppeareanceExecutionDone == NO) {
// Do your stuff
isfirstAppeareanceExecutionDone = YES;
}
}
#end
If I understand your question correctly, you can simply set a BOOL variable to recognize that viewDidAppear has already been called, ex:
- (void)viewDidAppear {
if (!self.viewHasBeenSet) { // <-- BOOL default value equals NO
// Perform whatever code you'd like to perform
// the first time viewDidAppear is called
self.viewHasBeenSet = YES;
}
}
This solution will call viewDidAppear only once throughout the life cycle of the app even if you create the multiple object of the view controller this won't be called after one time. Please refer to the rmaddy's answer above
You can either perform selector in viewDidLoad or you can use dispatch_once_t in you viewDidAppear. If you find a better solution then please do share with me. This is how I do the stuff.
- (void)viewDidLoad {
[super viewDidLoad];
[self performSelector:#selector(myMethod) withObject:nil afterDelay:2.0];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
static dispatch_once_t once;
dispatch_once(&once, ^{
//your stuff
[self myMethod];
});
}
By reading other comments (and based on #rmaddy 's answer), I know this is not what OP asked for, but for those who come here because of title of the question:
extension UIViewController {
var isPresentingForFirstTime: Bool {
return isBeingPresented() || isMovingToParentViewController()
}
}
UPDATE
You should use this method in viewDidAppear and viewWillAppear. (thanks to #rmaddy)
UPDATE 2
This method only works with modally presented view controllers and pushed view controllers. it's not working with a childViewController. using didMoveToParentViewController would be better with childViewControllers.
You shouldn't have issues in nested view controllers with this check
extension UIViewController {
var isPresentingForFirstTime: Bool {
if let parent = parent {
return parent.isPresentingForFirstTime
}
return isBeingPresented || isMovingFromParent
}
}
Try to set a BOOL value, when the situation happens call it.
#interface AViewController : UIViewController
#property(nonatomic) BOOL doSomeStuff;
#end
#implementation AViewController
- (void) viewWillAppear:(BOOL)animated
{
if(doSomeStuff)
{
[self doSomeStuff];
doSomeStuff = NO;
}
}
in somewhere you init AViewController instance:
AddEventViewController *ad = [AddEventViewController new];
ad.doSomeStuff = YES;
Not sure why you do this in ViewDidAppear? But if you want doSomeStuff is private and soSomeStuff was called only once, here is another solution by notification:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(doSomeStuff) name:#"do_some_stuff" object:nil];
- (void) doSomeStuff
{}
Then post when somewhere:
[[NSNotificationCenter defaultCenter] postNotificationName:#"do_some_stuff" object:nil];
swift 5
I've tried isBeingPresented() or isMovingToParent.
But It doesn't work.
So I tried below code. and It's work for me!
override func viewDidAppear(_ animated: Bool) {
if (self.isViewLoaded) {
// run only once
}
}
You can use this function in ViewDidLoad method
performSelector:withObject:afterDelay:
it will call that function after delay. so you don't have to use any custom timer object.
and For once you can use
dispatch_once DCD block.Just performSelector in the dispatch_once block it will call performSelector only once when ViewDidLoad is called
Hope it helps
I have MainController which is the (UIViewController) main view in the app, and MenuController which is a UITableView.
In the MainController.h
- (void) menu1:(NSInteger ) row;
In the MainController.m
- (void) menu1:(NSInteger ) row{
switch(row){
case 0:
//DO SOMETHING.......
break;
default:
break;
}
}
I want "menu1" to make action when I click a cell in the MenuController.
I made this: (in MenuController.m)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.section == 0){
[menu1:indexPath.row]; //<=== What should I do to make it work ?
}
}
You can access the method using your UINavigationController.
So in your MainController.h, add this:
- (void) menu1:(NSInteger)row;
Now in your MenuController.m:
#import "MainController.h";
and change didSelectRowAtIndexPathto:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.section == 0){
MainController *mC = [self.navigationController.viewControllers objectAtIndex:0]; // Change the objectAtIndex number to the number of your MainController in the navigationController view hierarchy
[mC menu1:indexPath.row];
}
}
Your menu1 method is an instance method on the MainController, so you'll want to send the message to an instance of that class. Like so:
MainController *mainVC = [[MainController alloc] init];
[mainVC menu1:indexPath.row];
Or, if you were to define your menu1 method as a class method, you could just send the message to the MainController without initializing. Use plusses instead of minuses when defining your menu1 method, then call like this:
[MainController menu1:indexPath.row];
However, this probably isn't the best way for you to pass data back and forth between View Controllers. You'll likely want to at the very least set a property on your MenuController, and then send the message to that (of course, setting the property wherever it makes sense).
[self.mainController menu1:indexPath.row];
But another really good method for calling a method on another View Controller is the delegate pattern, but I'll leave that up to you to research on your own.
https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/Delegation.html
in your MenuController.h
You get back to your previous view like this.
[[self navigationController] popToViewController:yourController animated:YES];
or
[self.navigationController popToRootViewControllerAnimated:animated];
and use UINotificationCenter or Delegate pattern.
If you have no idea about them UINoitifcation is easier but Delegate pattern is better in this situation. I ll explain how to use UINotificationCenter.
Throw notification from your menuController like this.
[[NSNotificationCenter defaultCenter]
postNotificationName:#"yourNotificationName"
object:nil ];
This code is for catch notification write it down to your viewappear method.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(yourMethodAboutWhatYouWantToDoAfterCatchNotification:)
name:#"yourNotificationName"
object:nil ];
Do what you want to do after catch it
- (void) yourMethodAboutWhatYouWantToDoAfterCatchNotification:(NSNotification *) notification
{
// do your job.
}
And in viewDidDisappear remove it. Or you can catch it multiple times after time.
[[NSNotificationCenter defaultCenter] removeObserver:self name:#"yourNOtificationName" object:nil];
There are two ways to achieve this.
Implement a protocol, whose implementation should be there in MainController.m
In that implementation, you should call the method which you have in MainController.m.
Set the table views delegate to MainController instead of setting it as self (MenuController)
This will help to implement the delegate methods directly in the MainController.m, from which the menu1 method can be called.
Provided code below for the first way:
Create a protocol file, which will help to make a callback, and create a method.
//
// utilProtocol.h
// tempProject
//
#protocol utilProtocol <NSObject>
#optional
-(void)captureCellSelectForRow:(int)rowNumber;
#end
Now Import this file inside in MenuController.
#import "utilProtocol.h" // Inside MenuController
And create a variable for the protocol.
#property(readwrite,assign)id<utilProtocol>utilDelegate;
In MainController.h, Import the utilProtocol.h and have its delegate into it.
Don't forget to add utilProtocol
#import <UIKit/UIKit.h>
#import "utilProtocol.h"
#interface ViewController : UIViewController <utilProtocol>
#end
Now Implement the method in MainController.m
-(void)captureCellSelectForRow:(int)rowNumber
{
[menu1:rowNumber];
}
Also set the delegate for it when the tableVIew's object is created in MainController.m
[tableViewObject setUtilDelegate:self];
Now when ever didSelectRowAtIndexPath is called in MenuController, just call the method using protocol.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.section == 0){
[utilDelegate captureCellSelectedForRow:indexPath.row];
}
}
Using this, the method inside MainController can be called.
I have a routine in my iOS program that imports and manipulates a file from Dropbox. This can take some time (5-10 seconds) and it doesn't make sense to return the user to the normal UI while it's doing it, so I want to present a view letting the user know what the progress is.
From one VC, I use Dropbox's drop-in file picker, then load up a presented (modal VC) thus:
ZSImportVC *importVC = [[ZSImportVC alloc] init];
importVC.results = results;
[importVC setModalPresentationStyle:UIModalPresentationFormSheet];
[self presentViewController:importVC animated:YES completion:^{
[self performFetch];
}];
The VC (a bog-standard UIViewController), has a UILabel property:
#property (weak, nonatomic) IBOutlet UILabel *statusMessage;
In viewWillAppear: I can set the text of this label without any problem. The thing is, I want to keep changing this text as the process of manipulating the file continues.
The method that manipulates the file is called from viewDidAppear:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self processImport];
}
However, within the processImport method, the following has no effect:
self.statusMessage.text = #"Some text to update the user.";
So I created a method:
- (IBAction)updateStatus:(NSString *)message
{
[self.statusMessage setText:message];
NSLog(#"%#", message);
}
just to check what's going on. The NSLog shows that the method is being called okay, but the label text doesn't change. I tried adding:
[self.statusMessage setNeedsDisplay];
to the method, but that didn't help. I'm not using any private queues or background threads. I read somewhere that using NSNotification helps, so I tried adding this to viewDidLoad:
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(updateStatus:) name:#"updateStatus" object:nil];
Then changed the called method to:
- (void)updateStatus:(NSNotification *)message
{
[self.statusMessage setText:message.object];
NSLog(#"%#", message.object);
}
and called this from the main method with:
[[NSNotificationCenter defaultCenter] postNotificationName:#"updateStatus" object:#"Retrieving file from Dropbox" userInfo:nil];
I could see from the console messages that the updateStatus method is getting called, but still the text doesn't change. Clearly I'm missing something here. Any thoughts?
Check your ZSImportVC instances on Debug perspective.
I think u are sending [self.statusMessage setText:message.object];
to another instance, that it is not shown on the screen.
I mean,
put a debug point here:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self processImport]; /* Debug point here*/
}
and check what´s the hexadecimal direction for self.
Now , do the same here:
- (void)updateStatus:(NSNotification *)message
{
[self.statusMessage setText:message.object]; /* Debug point here*/
NSLog(#"%#", message.object);
}
Btw, I had some problems with
[[NSNotificationCenter defaultCenter] postNotificationName:#"updateStatus" object:#"Retrieving file from Dropbox" userInfo:nil];
because the instance that receive this notification was not the correct.
I fixed that calling a normal method, but u maybe could not do that.
Sorry for my english :S
I have an NSTimer that runs every 10 seconds and is kicked off from LandingController.m. It continues to run as you go to other views in the application. I want to be able to (when a certain condition is met within that timer) update a label field from another view GuardMenu.m The label I want to update is called CurrentZone.text and I want to update it from value "N" to value "Y."
Here's my timer on LandingController.m
self.messageTimer = [NSTimer scheduledTimerWithTimeInterval:10.0
target:self
selector:#selector(checkForMessages)
userInfo:nil
repeats:YES];
Which calls this on LandingController.m
- (void)checkForMessages
{
if ( //some condition here ){
//update CurrentZone.text label in GuardMenu view and set equal to "Y"
} else {
//no need to update label in GuardMenu as it's currently equal to "N"
}
}
First create a NSNotification in your init method of GuardMenu class
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(receiveNotification:) name:#"TextChangeNotification" object:nil];
}
return self;
}
Then implement the notification's selector, this is where you will be changing your CurrentZone label text.
- (void)receiveNotification:(NSNotification *) notification {
if ([[notification name] isEqualToString:#"TextChangeNotification"]) {
NSLog (#"Change you label here");
self.lblCurrentZone.text = #"Y";
}
}
Now in your LandingViewController.m -viewDidLoad Method
Start the timer.
self->msgTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(checkForMessages) userInfo:nil repeats:YES];
Now implement the #selector for the NSTimer, this is where you will be sending the notification back to the GuardMenu class
- (void)checkForMessages {
NSString *strText = #"test";
if ([strText isEqualToString:#"test"]){
[[NSNotificationCenter defaultCenter] postNotificationName:#"TextChangeNotification" object:nil];
}
else {
}
}
NOTE: the NotificationName should be the same.
Sample Project Code Dropbox Link
You can use the prepareForSegue method to pass objects between view controllers in the storyboard. For example, to pass a string from the GreyViewController to the OrangeViewController, in GreyViewController.m you have:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
OrangeViewController *orange = [segue destinationViewController];
orange.self.orangeString = #"text for orangeView";
}
Then in the viewDidLoad of the other view controller, in the OrangeViewController.m, you can set the text of the label by doing the following:
self.orangeLabel.text = self.orangeString;
Maybe you should describe which error you're getting. Is your checkForMessages method (not) firing? Use an NSLog() message to check. Otherwise, check if the UILabel you want to change is actually loaded into memory (i.e. is not nil). Please also let us know if the currentZone.text is part of the view hierarchy of the LandingController or of another view controller.
You can make use of notifications.
In GuardMenu class init register for custom notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveNotification:)
name:#"MessageChangeNotification"
object:nil];
In LandingController->checkForMessages method post the notification when condition is satisfied.
[[NSNotificationCenter defaultCenter] postNotificationName:#"MessageChangeNotification"
object:nil];
In GuardMenu class implement the notification callback selector
- (void) receiveNotification:(NSNotification *) notification
{
if ([[notification name] isEqualToString:#"MessageChangeNotification"]) {
NSLog (#"Successfully received the notification");
//Change the label text here..
}
}
Hope it helps!
Amar.
Make sure that the label you are trying to edit is declared as a property in the appropriate view and properly synthesised. Also make sure it is connected in Interface Builder.
In GuardMenu.h
#property (strong, nonatomic) IBOutlet UILabel *CurrentZone;
Also, in LandingController.h, import GuardMenu.h:
#import "GuardMenu.h"
You will now be able to access the label and its text property from LandingController.h using
-(void)checkForMessages
{
GuardMenu *guardMenu = [[GuardMenu alloc]init];
if (/* some condition here */) {
//update CurrentZone.text label in GuardMenu view and set equal to "Y"
guardMenu.CurrentZone.text = #"Y";
} else {
//no need to update label in GuardMenu as it's currently equal to "N"
}
}
For this you should use KVO(Key Value Observing). There are lot of ways to pass notifications, but KVO is potentially much simpler. I suspect that Notification is used more often because you can do a ‘chain of responsibility’ for an event as opposed to just assigning an observer. However, just having an observer in a controller that can watch a particular property in another object and get notified of changes is a powerful and simple way to solve a whole class of problems.
Firstly set a public property in LandingController like "lablelText" .
Then add the observer once, when you create the LandingController view. Once you've added the observer, the observeValueForKeyPath:ofObject:change:context: method will be executed in GuardMenu, so you can do the update to the GuardMenu UI from there. You shouldn't need to do anything every time GuardMenu is about to appear.
In GuardMenu, you should probably create LandingController just before you are going to push LandingController onto the controller stack, presumably in the event handler for some action the user took. Immediately after you create LandingController, add the observer in GuardMenu with the correct NSKeyValueObservingOption value.
If you just want to be notified whenever the public property "lablelText" in LandingController is changed, then try this:
LandingController
#interface LandingController : UIViewController {
}
#property (strong, nonatomic) NSString* lablelText;
- (void)checkForMessages;
#end
#implementation LandingController
#synthesize lablelText;
- (void)checkForMessages
{
if ( //some condition here ){
//update CurrentZone.text label in GuardMenu view and set equal to "Y"
self.lablelText = #"Y";
} else {
//no need to update label in GuardMenu as it's currently equal to "N"
self.lablelText = #"N";
}
}
#end
GuardMenu
#interface GuardMenu : UIViewController {
}
#property (strong, nonatomic) IBOutlet UILabel* nameLabel;
- (IBAction) methodToHandleEvent:(id)sender;
#end
#implementation GuardMenu
- (IBAction) methodToHandleEvent:(id)sender{
LandingController* tempVC = [[LandingController alloc]init];
[tempVC addObserver:self forKeyPath:#"lablelText" options:NSKeyValueObservingOptionNew context:NULL];
[self.navigationController pushViewController:tempVC animated:YES];
}
- (void) observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context {
// Here you will be notified everytime lablelText changes
if ([keyPath isEqual:#"lablelText"]) {
NSString* changedName = [change objectForKey:NSKeyValueChangeNewKey];
// do something with the changedName - call a method or update the UI here
self.nameLabel.text = changedName;
}
}
#end
As an alternative for this you can use NSNotificationCeneter to pass notifications from one class to another for some event.
For this you can check my detailed answer How to pass Notifications from one class to another for some event.
Hope it helps you.
Create a notification in the init of GuardMenu class
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveNotification:)
name:#"UpdateCurrentZoneNotification"
object:nil];
In the LandingController,
(void)checkForMessages
{
if ( //some condition here ){
[[NSNotificationCenter defaultCenter] postNotificationName:#"UpdateCurrentZoneNotification"
object:nil];
//update CurrentZone.text label in GuardMenu view and set equal to "Y"
} else {
//no need to update label in GuardMenu as it's currently equal to "N"
}
}