Domanda

I have a view controller, that is called from several other view controllers. This view controller contains a UITextField, which collects different information, depending on which view controller has called it. The information has to be stored after it was collected. To be as independent as possible, the method to store the information should be located in the calling view controller. Thus, I use the following code in the method to collect the information:

- (void) collectContent
{
    NSString *info = [textField text];
    [textField resignFirstResponder];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"NewValueA" object:info];

    [[self navigationController] popToRootViewControllerAnimated:YES];
}

In the calling view controller, I have the following line in its init method:

- (id) init
{
    ...
    if (self)
    {
        ...
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(storeNewValueA) name:"NewValueA" object:nil];
    }
return self;
}

But now, I want to use this view controller from another view controller, to collect ValueB or ValueC. How do I reference the calling view controller to call a method for storing the collected value just there? I want to decide, that if the view controller was called from vcB, the entered value must have been valueB, an so on...

È stato utile?

Soluzione

You can create a protocol for this commonly used view controller and implement this protocol by the calling view controllers :

@protocol TextFieldViewControllerDelegate : NSObject {
    - (void)contentCollected;
}

In your text field (the common) view controller define a delegate property:

@property (nonatomic, strong) id<TextFieldViewControllerDelegate> delegate;

The calling view controller will set itself as the delegate and implement the needed method:

- (void) contentCollected:(NSString *)value
{
    // Store the value where needed
}

In the common (textfield) view controller notify the delegate when needed :

- (void) collectContent
{
    NSString *info = [textField text];
    [textField resignFirstResponder];

    [_delegate contentCollected:info];

    [[self navigationController] popToRootViewControllerAnimated:YES];

    _delegate = nil;
}

This way your common view controller does not need to know which view controller called it. Using the delegate the calling view controller will be notified.

Altri suggerimenti

Hm, if you want to persist this simple string even when the application was close, I would use NSUserDefaults:

Store the string:

[[NSUserDefaults standardUserDefaults] setObject:@"MyValue" ForKey:@"USER_DEFAULTS_VIEWCONTROLLER_VALUES"];
[[NSUserDefaults standardUserDefaults] synchronize];

Get the string:

[[NSUserDefaults standardUserDefaults] objectForKey:@"USER_DEFAULTS_VIEWCONTROLLER_VALUES"];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top