How to use NSMutableArray from Master Controller in Detail Controller - ios

I am using UISplitViewController and I have a Master Controller and Detail Controller.
The Master Controller I have a NSMutableArray defined like so:
#import "MasterController.h"
#import "DetailController.h"
#interface MasterController ()
#property NSMutableArray *objects;
#end
#implementation MasterController
and I am trying to call it in my Detail Controller like so:
#import "DetailController.h"
#import "MasterController.h"
#interface DetailController ()
{
MasterController *purchaseOrder;
}
#end
#implementation DetailController
- (void)GetRequest
{
NSArray *tableData = [dataSource.areaData GetPurchaseOrderItems:[NSString stringWithFormat:#"%#%#",areaPickerSelectionString,unitPickerSelectionString]];
NSLog(#"%#", tableData);
//TODO: foreach tableData populate object.
[purchaseOrder object];
}
ultimately I am looking to populate the object with each item in tableData. But when I call object, I get this error:
No visible #interface for 'LHPurchaseOrderMaster' declares the selector 'object'
how would I accomplish what I am trying to accomplish ?

So many things amiss here. A few short pointers to hopefully help:
You've put #property NSMutableArray *objects; in your private interface. Try moving this to the header file and making it public. Any reason why you haven't declared this as #property (nonatomic, strong) NSMutableArray *objects; ?
The syntax [someInstance someMethod] means that your purchaseOrder instance of MasterController is trying to call a method called object of which you've not provided us any details about. Perhaps you're trying to call objects instead. But this will only work if you make it public as noted above.
If you're attempting to design a better API than that, you can keep your NSMutableArray of objects private, and provide a public NSArray of maybe *allObjects and inside yourDetailController a getter method like
- (NSArray*)allObjects {
return [self.objects copy];
}
You've not provided any information about LHPurchaseOrderMaster, but hopefully I'm on the right track with helping you solve your problem here.

Related

Objective-C Code Structure in Implementation File

#interface OuterSpaceController ()
//Cannot alloc and init my array here for some reason
NSMutableArray *spaceObjectsAsPropertyLists = [[NSMutableArray alloc] init];
#end
//But could do it here... Can someone explain why this is the case?
NSMutableArray *spaceObjectsAsPropertyLists = [[NSMutableArray alloc] init];
#implementation OuterSpaceController
#end
Hi I had a question regarding this code structure in objective-C. My first question is why is this portion even present in the implementation file?:
#interface OuterSpaceController ()
#end
I tried creating my NSMutableArray there^^^, so I can access it in all my methods in the implementation file, but I was not able to for some reason. Also regarding my NSMutableArray if I create it in between the #end and #implementation OuterSpaceController lines of code (like shown in my first block of code), will my NSMutableArray be allocated and initialized every time my view controller is loaded in memory? And if not when does the allocation and initialization of this NSMutableArray *spaceObjectsAsPropertyLists Mutable Array happen?
Thank you so much for the help in advance!
This is called a class extension:
#interface OuterSpaceController ()
#end
Extensions allow you to add declarations to your class. See Apple's docs for details. This is mostly used for declaring properties or methods in a different scope of the original declaration. Something like this:
// Foo.h
#interface Foo
#property (strong) NSArray * everyoneCanSeeThis;
#end
// Foo.m
#interface Foo ()
#property (strong) NSArray * thisIsOnlyVisibleInThisFile;
#end
There are other uses to extensions. I recommend you read Apple's docs.
Your other question is not related to this. In order to initialise the spaceObjectsAsPropertyLists property you have two options. One, when initialising the class:
#interface OuterSpaceController ()
// Does not initialise, just declares. This is an interface, not an implementation
#property (strong) NSMutableArray *spaceObjectsAsPropertyLists;
#end
#implementation OuterSpaceController
- (instancetype)init
{
self = [super init];
if (self) {
_spaceObjectsAsPropertyLists = [NSMutableArray array];
}
return self;
}
#end
In this case the array is instantiated as soon as the class is initialised, but there's a second option. There's another way of initialising classes called Lazy Initialisation. Here's how it goes:
#interface OuterSpaceController ()
// Does not initialise, just declares. This is an interface, not an implementation
#property (strong) NSMutableArray *spaceObjectsAsPropertyLists;
#end
#implementation OuterSpaceController
- (instancetype)init
{
// Do not instantiate!
return [super init];
}
- (NSMutableArray *)spaceObjectsAsPropertyLists
{
if (_spaceObjectsAsPropertyLists == nil) {
_spaceObjectsAsPropertyLists = [NSMutableArray array];
}
return _spaceObjectsAsPropertyLists;
}
#end
The general idea is to override the property's getter. The upside of this method is that the property will be initialised only as soon as it is needed, and not sooner. This method is usually more memory friendly.
You need to know that your interfaces can only contain declarations. It's the implementation section who's responsible for pretty much everything else.

Swift accessing and updating tableview in container view

This is kind of confusing but I will do my best to explain. I have a view controller with a container view. In the container view is a table view. I want to update the tableview from the main view controller. For example, the table view will contain a list of names. As the user types in a name into a text field, the table view will update to find names that match what the user inputed.
The main question is:
How can I update the table view from the main view controller?
Note: I can't use prepare for segue because the data will be changing.
I figured it out...
I can access the view through childviewcontrollers. Here's the code I used:
let childView = self.childViewControllers.last as! ViewController
childView.List = self.nameList
childView.tableView.reloadData()
This is actually a beginner question and I would be happy to help. You need to find a place to store your data and then you can access it based on your need. That's what we normally call model.
You can take advantage of one of the design patter: shared instance. It will be existing during the application life cycle. See the following example.
You can have a model class like this:
// .h
#interface DataManager : NSObject
+ (instancetype)sharedManager;
#property (strong, nonatomic, readonly) NSMutableArray *data;
#end
// .m
#interface DataManager : NSObject
#property (strong, nonatomic, readwrite) NSMutableArray *data;
#end
#implementation DataManager
+ (instancetype) sharedManager {
static DataManager *sharedInstance = nil;
static dispatch_once_t dispatchOnce;
dispatch_once(&dispatchOnce, ^{
sharedInstance = [[self alloc] init];
sharedInstance.data = [[NSMutableArray alloc] initWithCapacity:5];
});
return sharedInstance;
}
#end
Using this, you can access your data via your main view controller or your presenting view controller.

Connecting data from different ViewController with same parents

So I have 2 different table views that use the same array (the array is originally created in the Role table view, the below one). How can I connect those two?
(Usually I use prepareForSegue to pass the data but since there is no segue, I'm not sure how can I do this)
EDIT 1: Add the location of the array.
What is a Model and why you need it
In most of the cases it's useless to pass data around if you don't have a Data Model. You can store your data using a technique called Data Persistence.
An example of a pattern you could use is MVC.
MVC or model-view controlelr is an software pattern widely using when making iOS Apps. In this architectural pattern your Controllers are a bridge between your View and your Model.
In this specific scenario both UITableViewControllers would use the same Model but they would display this data differently.
Persisting your Model
There are several ways to do that, the way I like the most is a little framework called CoreData, you can see this question for some reference on that.
You can also refer to this question to see the use of Singletons. But keep in mind that singletons alone do not persist the data. You'll have to add some sort of mechanism if you want the data to remain there between app sessions.
Persisting user preferences
The simplest way to store small chunks of data is using NSUserDefaults (but it's only meant to store defaults):
Let's assume you have an array
NSArray* testArray = #[#"first", #"second", #"third"];
You can set it to a key by using
[[NSUserDefaults standardUserDefaults] setObject:testArray forKey:#"myArray"];
You can sync NSUserDefaults using
[[NSUserDefaults standardUserDefaults] synchronize];
Then, anywhere in your app you can read it doing
[[NSUserDefaults standardUserDefaults] objectForKey:#"myArray"]
Passing data through the app
On the other hand you have to pass your data around somehow. To do so you can use formal protocols, specifically delegates.
As per the Apple documentation:
In a delegate-based model, the view controller defines a protocol for
its delegate to implement. The protocol defines methods that are
called by the view controller in response to specific actions, such as
taps in a Done button. The delegate is then responsible for
implementing these methods. For example, when a presented view
controller finishes its task, it sends a message to the presenting
view controller and that controller dismisses it.
Using delegation to manage interactions with other app objects has key
advantages over other techniques:
The delegate object has the opportunity to validate or incorporate
changes from the view controller.
The use of a delegate promotes
better encapsulation because the view controller does not have to know
anything about the class of the delegate. This enables you to reuse
that view controller in other parts of your app.
For more information on passing data through view controllers (the main point of this question) take a look at this SO answer.
You should never use data persistence just to pass data through the app. Neither user defaults nor core data.
Also using singletons is not good choice. All will mess up your memory.
Instead use call backs — either as delegates or blocks.
Or use unwind segues.
I explain delegates and unwind segues here: Passing row selection between view controllers
this example passes index paths, as it is appropriate in that situation, but the passed object might be of any type or size, as only pointers are passes.
if you use the NSUserDefaults on the other side, data is copied and written to the disk — there for data is copied and slowly processed — without any use.
I created a sample app how to pass data from one view controller to another view controller in another tab bar branch.
click to enlarge
TabBarController
We need to intercept the section of view controllers to set up some callback mechanism. In this case I am using blocks, but delegate would work as-well.
UITabController has a purely optional delegate. I create a subclass of UITabBarController to serv as it's own delegate, but actually a separate delegate should work in the same way.
#import "GameTabBarController.h"
#import "RoleViewController.h"
#interface GameTabBarController () <UITabBarControllerDelegate>
#end
#implementation GameTabBarController
-(void)viewDidLoad
{
[super viewDidLoad];
self.delegate = self;
}
-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
if ([viewController isKindOfClass:[UINavigationController class]]) {
UINavigationController *navController = (UINavigationController *)viewController;
if ([navController.topViewController isKindOfClass:[RoleViewController class]]) {
RoleViewController *rvc = (RoleViewController *)[navController topViewController];
[rvc setSelectedRole:^(Role *role) {
UIViewController *viewController = self.viewControllers[0];
[viewController setValue:role forKey:#"role"];
[self setSelectedIndex:0];
}];
}
}
return YES;
}
#end
I set the initial tab bar controller to this sub class
Role, RoleDatasource and RoleViewController
The RoleViewController displays a list of Roles, but the datasource and delegate for it's table view are a separate class that I add to the role view controller scene in the storyboard, where i also were it up.
Role
#interface Role : NSObject
#property (nonatomic,copy, readonly) NSString *name;
-(instancetype)initWithName:(NSString *)name;
#end
#import "Role.h"
#interface Role ()
#property (nonatomic,copy) NSString *name;
#end
#implementation Role
- (instancetype)initWithName:(NSString *)name
{
self = [super init];
if (self) {
_name = name;
}
return self;
}
#end
RoleDatasource
#import <UIKit/UIKit.h>
#class Role;
#interface RoleDatasource : NSObject <UITableViewDataSource, UITableViewDelegate>
#property (nonatomic, copy) void(^roleSelector)(Role *role);
#end
#import "RoleDatasource.h"
#import "Role.h"
#interface RoleDatasource ()
#property (nonatomic,strong) NSArray *roles;
#end
#implementation RoleDatasource
- (instancetype)init
{
self = [super init];
if (self) {
_roles = #[[[Role alloc] initWithName:#"Magician"], [[Role alloc] initWithName:#"Soldier"], [[Role alloc] initWithName:#"Maid"]];
}
return self;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.roles.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"RoleCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
cell.textLabel.text = [self.roles[indexPath.row] name];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.roleSelector(self.roles[indexPath.row]);
}
#end
RoleViewController
#import <UIKit/UIKit.h>
#class Role;
#interface RoleViewController : UIViewController
#property (nonatomic, copy) void(^selectedRole)(Role *role);
#end
#import "RoleViewController.h"
#import "RoleDatasource.h"
#interface RoleViewController ()
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#end
#implementation RoleViewController
- (void)viewDidLoad {
[super viewDidLoad];
RoleDatasource *roleDataSource = (RoleDatasource *)[self.tableView dataSource];
[roleDataSource setRoleSelector:^(Role *role) {
self.selectedRole(role);
}];
}
#end
PlayViewController
As soon as a role is selected on the role view controller we want to tell our tab bar controller to switch to the game view controller and show the selected role there, see the code for the tab bar controller.
The GameViewController is just a simple view controller subclass that has a property to hold a role and if a role is set, it will displays it name.
#import <UIKit/UIKit.h>
#class Role;
#interface PlayViewController : UIViewController
#property (nonatomic, strong) Role *role;
#end
#import "PlayViewController.h"
#import "Role.h"
#interface PlayViewController ()
#property (weak, nonatomic) IBOutlet UILabel *roleNameLabel;
#end
#implementation PlayViewController
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.roleNameLabel.text = (self.role) ? self.role.name : self.roleNameLabel.text;
}
#end
You'll find an example on github.
I think that I should put the array in the Tab bar Controller and connect it to the Role Table view (in order to maintain the behaviour like it is before) and connect it to my new Table view to do what I want to do.
The only problem I can think of is that since my program is small, adding this will not be a big problem. But if I have more vc, it's going to be so much pain.

how to pass the variable in segue

i have defined variable in GroupView.h
#interface GroupView()
{
NSMutableArray *chatrooms;
}
#end
#implementation GroupView
Now i want to pass this variable in segue
#interface FriendsViewController ()
#end
#implementation FriendsViewController
else if ([segue.identifier isEqualToString:#"showGroupView"]) {
GroupView *groupView = (GroupView *)segue.destinationViewController;
groupView.chatrooms = [NSMutableArray arrayWithArray:chatrooms];
}
i know that chatrooms has to be property in header file to code this way but it is not
So is there any way to use this variable in segue.
Thanks for help.
chatrooms defined as an ivar like you have done is accessed using -> notation:
groupView->chatrooms = [NSMutableArray arrayWithArray:chatrooms]
This is generally discouraged, though. You should use a property instead:
#interface GroupView
#property (strong) NSMutableArray *chatrooms;
#end
Incidentally, if you're using an NSMutableArray, that indicates that you want to modify the element list of the array directly and not just replace the array wholesale. If you only ever want to replace the array with a whole new array every time, I suggest using NSArray instead.
Another point to make here is that you're attempting to cast the object held at segue.destinationViewController as a GroupView. You have either named a UIViewController subclass in a very misleading way, or you are not accessing the GroupView as a correct member of the UIViewController that is returned to you.
Normally, if you are not building the SDK or something. You don't really have a better reason not to expose it in the header file. However, you can expose the property in the extension and declare a private property in the host class(It's really not able to pass if you just declare a local variable). For example, You have a extension called GroupView+Helper. So, you can pass it into the property exposed in the extension. And then internally translate into the GroupView.
In GroupView.m:
#interface GroupView
#property (strong, nonatomic) NSMutableArray *chatrooms;
#end
In GroupView+Helper.h
#property (strong, nonatomic) NSMutableArray *internalChatrooms;
Also, you need to import the GroupView+Helper in the GroupView.
It will make your chatrooms private and internalChatrooms protected.

Getting View Controller to retrieve data from a data model file

I'm pretty new to programming. I am creating a very simple iOS Quiz app just for practice. Here is what I have gotten done thus far:
I created the Xcode project using the "Single View" template. Thus, I already have the appDelegate files, the View Controller and a View (XIB file).
My view only has four controllers: 2 UILabels and 2 UIButtons. Each button is paired up with a label. I have all the connections for these 4 controllers setup. When the user taps the button labelled "Get a State" it needs to populate it's label with the name of a state I have in an NSMutableArray called stateArray. When the user taps on the button labelled "Get Capital" is needs to populate it's label with the state's capital in it's label.
I created an Objective-C class that inherits from NSObject to hold my data model called dataModel. In the dataModel.m file I have created and populated the two arrays.
In the view controller .m file I imported the dataModel.h file.
The only problem I am having is getting the view controller to retrieve data from the dataModel file. I have read that I should probably be using Delegation, but I am just looking to know how to do it more simply...I ready something about the view controller and the data model file should have references to each other? If so, what would the coding look like?
Here is my coding thus far:
#import <UIKit/UIKit.h>
#interface onMyOwnViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *stateField;
#property (weak, nonatomic) IBOutlet UILabel *answerField;
- (IBAction)answerButton:(id)sender;
- (IBAction)stateButton:(id)sender;
#end
#import "onMyOwnViewController.h"
#import "dataModel.h"
#implementation onMyOwnViewController
- (IBAction)stateButton:(id)sender
{
NSString *myState = [stateArray objectAtIndex:0]; //this line produces an error.
[_stateField setText:myState];
[_answerField setText:#"hi"];
}
- (IBAction)answerButton:(id)sender
{
}
#end
Below is my dataModel coding:
#import <Foundation/Foundation.h>
#interface dataModel : NSObject
#property(nonatomic, strong) NSMutableArray *answerArray;
#property(nonatomic, strong) NSMutableArray *stateArray;
#end
#import "dataModel.h"
#import "onMyOwnViewController.h"
#implementation dataModel
- (id)init
{
self = [super init];
if(self){
_answerArray = [[NSMutableArray alloc]initWithObjects:#"Michigan", #"Illinios", nil];
_stateArray = [[NSMutableArray alloc]initWithObjects:#"Lansing", #"Springfield",
nil];
}
return self;
}
#end
When I run the app, everything works except retrieving data from the data model. When you replay, please reply with coding.
You need to create an instance of your dataModel in onMyOwnViewController.
#implementation onMyOwnViewController {
dataModel *data;
}
-(void)viewDidLoad {
data = [[dataModel alloc] init];
}
Then in your method call
- (IBAction)stateButton:(id)sender
{
NSString *myState = data.stateArray[0];
...
}

Resources