Reputation: 2816
I have two view controllers accessing one NSObject
with an NSMutableArray
. The first VC is a tableview that loads the array's objects, and the second VC is where I add more objects. When I popViewControllerAnimated
from my second VC to the first VC, the new object is lost and the first VC only loads the original array, even when I reload the tableView in viewWillAppear
.
NSMutableArray
from the second VC lost?NSMutableArray
where it can be accessed from any VC?I have a Groceries
class of type NSObject
, which has NSMutableArray *groceryList
.
// NSObject class
@interface Groceries : NSObject
@property (nonatomic, strong) NSMutableArray *groceryList;
@end
// First VC
#import "Groceries.h"
@interface TableViewController ()
@property (nonatomic, strong) Groceries *groceries;
@end
@implementation TableViewController
- (void)viewDidLoad {
[super viewDidLoad];
_groceries = [[Groceries alloc]init];
}
// Second VC
#import "Groceries.h"
@interface AddItemViewController ()
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (nonatomic, strong) Groceries *groceries;
@end
@implementation AddItemViewController
- (void)viewDidLoad {
[super viewDidLoad];
_groceries = [[Groceries alloc]init];
}
// When I press the return button, I'm popping back to First VC
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if([text isEqualToString:@"\n"]) {
[[_groceries groceryList]addObject:_textView.text];
[textView resignFirstResponder];
[[self navigationController]popViewControllerAnimated:YES];
return NO;
}
return YES;
}
@end
Upvotes: 0
Views: 558
Reputation: 2636
There are 2 ways you can approach this:
Create Groceries as singleton class and use the shared instance to update the array and it will be accessible in both the VC
Use delegation to pass data back to firstVC
Here is classic example for your situation: http://jameslin.herokuapp.com/blog/2013/10/15/hello-world/
You can use NSNotification update the array object, where VC1 will register for notification and VC2 will post the notification and send the notification object.
Upvotes: 2