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
.
- Why is the new object I'm passing into the
NSMutableArray
from the second VC lost? - How can I make sure I'm adding objects to the
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