Double click on row in NSTableView doesn't display the new view - objective-c

I have an os x app that uses core data.
I have 3 .xib files in my app, those are:
1. MainMenu.xib
2. MasterTableViewController.xib
3. DetailViewController.xib
When started , app displays a view that has NSTableView with couple of records in it.
I name that view MasterTableViewController
I want when user double click on the row, to hide the "master" view and to display my "detail" view. I named that view DetailViewController.
When double clicked on the row in the NSTableView in the "master" view,nothing happen, "master" view remains visible. What I want is "master" view to dissapear, and "detail" view to appear.
Here is the code that I have right now, and more explanations follows:
AppDelegate.h
#import <Cocoa/Cocoa.h>
#interface AppDelegate : NSObject <NSApplicationDelegate>
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (nonatomic,strong) NSViewController *mainAppViewController;
#property (weak) IBOutlet NSView *mainAppView;
- (void)changeViewController:(NSInteger)tag;
#property (weak) IBOutlet NSTableView *websitesTableView;
- (void)tableViewDoubleClick:(id)nid;
#end
AppDelegate.m
#import "AppDelegate.h"
#import "MasterTableViewController.h"
#import "DetailViewController.h"
#interface AppDelegate ()
#property (weak) IBOutlet NSWindow *window;
- (IBAction)saveAction:(id)sender;
#end
#implementation AppDelegate
NSString *const masterTable = #"MasterTableViewController";
NSString *const detail = #"DetailViewController";
-(void)awakeFromNib {
[_websitesTableView setTarget:self];
[_websitesTableView setDoubleAction:#selector(tableViewDoubleClick:)];
}
- (void)tableViewDoubleClick:(id)nid {
NSInteger rowNumber = [_websitesTableView clickedRow];
NSTableColumn *column = [_websitesTableView tableColumnWithIdentifier:#"websiteUrl"];
NSCell *cell = [column dataCellForRow:rowNumber];
NSInteger tag = 2;
[self changeViewController:tag];
}
- (void)changeViewController:(NSInteger)tag {
[[_mainAppViewController view]removeFromSuperview];
switch (tag) {
case 1:
self.mainAppViewController = [[MasterTableViewController alloc]initWithNibName:masterTable bundle:nil];
break;
case 2:
self.mainAppViewController = [[DetailViewController alloc]initWithNibName:detail bundle:nil];
break;
}
[_mainAppView addSubview:[_mainAppViewController view]];
[[_mainAppViewController view] setFrame:[_mainAppView bounds]];
[[_mainAppViewController view] setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// automatically run the master table view controller
NSInteger tag = 1;
[self changeViewController:tag];
}
Now, some of you may wondering, where is the rest of the code. I have ommited the boiler plate code for the core data below in the AppDelegage.m, since it is unchanged. I used binding to make my NSTableView to work and to display my records, so MasterTableViewController.h and .m files are empty, and same is true for the DetailViewController.h and .m file.
Important note - What i can't understand here: If I change the tag in 2 in the applicationDidFinishLaunching method, detail view is displayed normally, but if i switch it back on 1, and then double click on the row, "master" view (with the NSTableView) remains visible, and nothing happen (views are not swapped)
Anyone can help me to find out what is wrong with my code?
Regards, John

You apparently had a second instance of your AppDelegate class instantiated in the MasterTableViewController.xib file. There should be only one AppDelegate instance and that's the one in MainMenu.xib. So, it shouldn't be in MasterTableViewController.xib.
One of the instances was receiving the double-click action method from the table, but the other one was the one with the outlet to the main window.
You need(ed) to get rid of the second instance and find another way to access the app delegate from the MasterTableViewController.

Related

IBInspectable property values not updating in xib

I'm running into a minor complication using IBInspectable properties and not sure if it might have something to do with my xibs and xib usage. I'm trying to reuse a custom control between multiple view controllers. The control is a custom tab manager:
The IBInspectable Attributes are configured in this xib as: First, Second, Third.
Here is the corresponding code for the header file.
IB_DESIGNABLE
#interface TabContainerView : NSView
#property (nonatomic, strong) IBOutlet NSView *view;
#property (weak) IBOutlet TabContentView *contentView;
#property (weak) IBOutlet TabView *firstTab;
#property (weak) IBOutlet TabView *secondTab;
#property (weak) IBOutlet TabView *thirdTab;
#property (nonatomic, strong) IBInspectable NSString *tabOneText;
#property (nonatomic, strong) IBInspectable NSString *tabTwoText;
#property (nonatomic, strong) IBInspectable NSString *tabThreeText;
#end
#import "TabContainerView.h"
#interface TabContainerView ()
#property (nonatomic, strong) NSMutableArray *tabsArray;
#property (nonatomic, assign) NSInteger selectedTabIndex;
#property (weak) IBOutlet NSTextField *tabOneTextField;
#property (weak) IBOutlet NSTextField *tabTwoTextField;
#property (weak) IBOutlet NSTextField *tabThreeTextField;
#end
#implementation TabContainerView
#pragma mark Init
- (id)initWithFrame:(NSRect)frameRect {
NSString* nibName = NSStringFromClass([self class]);
self = [super initWithFrame:frameRect];
if (self) {
if ([[NSBundle mainBundle] loadNibNamed:nibName
owner:self
topLevelObjects:nil]) {
[self configureView];
}
}
return self;
}
#pragma mark Configure View
- (void)configureView{
[self.view setFrame:[self bounds]];
[self addSubview:self.view];
self.tabOneTextField.stringValue = self.tabOneText;
self.tabTwoTextField.stringValue = self.tabTwoText;
self.tabThreeTextField.stringValue = self.tabThreeText;
}
#end
This works fine in the TabContainerView.xib without issue. Now when I attempt to use this control in two different view controllers, I run into problems. Both of my view controllers are also loaded from Xibs.
In view controller 1 I have something like this:
In view controller 1 I've subclassed the custom view to the TabContainerView subclass which works just fine when I run the application. I've also changed the text to be specific for this view controller. List, Map, Filter are the IBInspectable property values for view controller one. In view controller 2 (not shown), I've done the exact same thing, however different IBInspectable property values specific for view controller 2. However, when I run the application the values never update and always stay as First, Second, and Third. I'm not sure if there is something I'm doing that's causing this problem but any help or tips would be appreciated. (IBDesignable seems to give me a lot of warnings where it breaks and not sure if maybe it's just loading the last saved value for the xib.)
Have you imported #import "TabContainerView.h" in controller 2 .h file.

KVO Method observeValueForKeyPath notifys me about the change, but I can't use it in viewDidLoad

I am working on this couple of days and I can't figure out what I am doing wrong.
First, I don't know if the KVO is the best way to pass the value of the clicked row info from one view controller to another view controller.
I have Main view, with 2 buttons only. Clicking on one of the buttons, I open MasterTableViewController, where I have the NSTableView with some records (one column only) from core data.
On click on the NSTableView, I am opening the DetailViewController, where I have only one label.
What I am trying is to change the label value, with the value of the clicked row in the NSTableView.
While I can print the value of the clicked row in the DetailViewController, I can't change the label value. I assume that notification comes before the viewDidLoad get called.
I have the following code:
In my MasterTableViewController.h file:
#import <Cocoa/Cocoa.h>
#import "AppDelegate.h"
#interface MasterTableViewController : NSViewController
#property (nonatomic,strong) NSManagedObjectContext *mObjContext;
#property (weak) IBOutlet NSTableView *websitesTableView;
- (IBAction)tableViewDoubleClick:(id)sender;
#property (nonatomic,strong) NSString *cellValue;
#end
In my MasterTableViewController.m file:
#import "MasterTableViewController.h"
#import "DetailViewController.h"
#interface MasterTableViewController ()
#end
#implementation MasterTableViewController
-(void)awakeFromNib {
[_websitesTableView setTarget:self];
[_websitesTableView setDoubleAction:#selector(tableViewDoubleClick:)];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Get the object managed context
AppDelegate *appDelegate = (AppDelegate*)[[NSApplication sharedApplication] delegate];
self.mObjContext = appDelegate.managedObjectContext;
}
- (IBAction)tableViewDoubleClick:(id)sender {
NSInteger rowNumber = [_websitesTableView clickedRow];
NSTableColumn *column = [_websitesTableView tableColumnWithIdentifier:#"websiteUrl"];
NSCell *cell = [column dataCellForRow:rowNumber];
_cellValue = [cell stringValue];
MasterTableViewController *mtvc = [[MasterTableViewController alloc]initWithNibName:#"MasterTableViewController" bundle:nil];
DetailViewController *dvc = [[DetailViewController alloc]initWithNibName:#"DetailViewController" bundle:nil];
[mtvc addObserver:dvc
forKeyPath:#"cellValue"
options:NSKeyValueObservingOptionNew
context:NULL];
[mtvc setCellValue:_cellValue];
[mtvc removeObserver:dvc forKeyPath:#"cellValue"];
AppDelegate *appDelegate = (AppDelegate*)[[NSApplication sharedApplication] delegate];
[appDelegate changeViewController:2];
}
#end
Code for the DetailViewController.h is:
#import <Cocoa/Cocoa.h>
#import "AppDelegate.h"
#interface DetailViewController : NSViewController
#property (nonatomic, weak) AppDelegate *appDelegate;
#property (weak) IBOutlet NSTextField *detailLabel;
#property (nonatomic,strong) NSString *transferedLabelValue;
#property (nonatomic,strong) NSString *cellValue;
#end
Code for the DetailViewController.m is:
#import "DetailViewController.h"
#import "MasterTableViewController.h"
#interface DetailViewController ()
#end
#implementation DetailViewController
- (void)viewDidLoad {
[super viewDidLoad];
// if I uncomment this line, program crashes, because the value of the _transferedLabelValue is null here.
//[_detailLabel setStringValue:_transferedLabelValue];
}
-(void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if ([keyPath isEqualToString:#"cellValue"]) {
_transferedLabelValue = [change objectForKey:NSKeyValueChangeNewKey];
// Here I get the value of the clicked cell, it is printed in the console. However if I try to change the label value here, doesn't work, since seems that label does not exist yet at this point....
NSLog(#"Value in the observerValueForKeyPath is:%#",_transferedLabelValue);
}
}
#end
Code from the AppDelegate.h :
#import <Cocoa/Cocoa.h>
#interface AppDelegate : NSObject <NSApplicationDelegate>
#property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
#property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
#property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (weak) IBOutlet NSView *mainAppView;
#property (nonatomic,strong) NSViewController *mainAppViewController;
- (IBAction)showMasterViewButtonHasBeenClicked:(id)sender;
- (IBAction)showDetailViewButtonHasBeenClicked:(id)sender;
- (void)changeViewController:(NSInteger)tag;
#end
Here is only the relevant code from the AppDelegatge.m, the boiler plate code is omited.
#import "AppDelegate.h"
#import "MasterTableViewController.h"
#import "DetailViewController.h"
#interface AppDelegate ()
#property (weak) IBOutlet NSWindow *window;
- (IBAction)saveAction:(id)sender;
#end
#implementation AppDelegate
- (IBAction)showMasterViewButtonHasBeenClicked:(id)sender {
NSInteger tag = [sender tag];
[self changeViewController:tag];
}
- (IBAction)showDetailViewButtonHasBeenClicked:(id)sender {
NSInteger tag = [sender tag];
[self changeViewController:tag];
}
- (void)changeViewController:(NSInteger)tag {
[[_mainAppViewController view]removeFromSuperview];
switch (tag) {
case 1:
self.mainAppViewController = [[MasterTableViewController alloc]initWithNibName:#"MasterTableViewController" bundle:nil];
[_mainAppView addSubview:[_mainAppViewController view]];
[[_mainAppViewController view] setFrame:[_mainAppView bounds]];
[[_mainAppViewController view] setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
break;
case 2:
self.mainAppViewController = [[DetailViewController alloc]initWithNibName:#"DetailViewController" bundle:nil];
[_mainAppView addSubview:[_mainAppViewController view]];
[[_mainAppViewController view] setFrame:[_mainAppView bounds]];
[[_mainAppViewController view] setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
break;
}
}
Again, if the KVO and notification is not the best way to go, please let me know how I should "inform" the other view which row has been clicked and which is his value.
Regards, John
I manage to solve my problem with the KVO...My problem was that I was creating new instances of the view controllers in the MasterTableViewController...What I did was I created properties for the ViewControllers in the appDelegatge.h like this:
#property MasterTableViewController *mtvc;
#property DetailViewController *dvc;
and then in the appDelegate.m :
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
_mtvc = [[MasterTableViewController alloc]initWithNibName:#"MasterTableViewController" bundle:nil];
_dvc = [[DetailViewController alloc]initWithNibName:#"DetailViewController" bundle:nil];
}
Rest of the changes in the code are just replacing the MasterTableViewController and DetailViewController with _mtvc and _dvc...
However...I had been warned that this solution is error prone, and that warning shows true. It happens from time to time that I get wrong value, not the clicked one. Once in 4-5 clicks, I get wrong value. What makes me confuse is that I make the function to work on double click, but it works on single click as well...But those things are for some other question I guess.

How to change NSMenuItem Title (Login to Logout)

Im surprised that this hasn't already been asked:
But how does one go about changing the NSMenuItem title in a NSStatusBar menu. When a user logs in I want the menu item to say logout. I have tried creating an outlet to modify my NSMenuItem as a would a label or something.
AppDelegate.h
#property (retain) IBOutlet NSMenuItem *loginItem;
AppDelegate.m
[loginItem setTitle:#"Logout"];
But that didnt work.
The only thing that I was able to do was delete the old NSMenuItem, then add a new one, but it would just add it to the bottom. Is the only way to do this to remove every menu item then re-add them?? That seems very inefficient.
The method you describe should work, though, in general, keeping IBOutlets for all your menu items can be tedious. (If your solution isn't working, make sure the IBOutlet is actually connected in the nib file, and make sure that you're setting the title at an appropriate time. If you're trying to set it in your controller's init method, for example, that's too early on, and the outlets haven't yet been connected up: move the method to awakeFromNib or similar.
A better approach in the long run is to use the <NSMenuDelegate> protocol and NSMenuValidation (informal) protocol to update menu items dynamically (and lazily).
For example, define your controller class like the following:
#interface MDAppDelegate : NSObject <NSApplicationDelegate, NSMenuDelegate>
#property (strong) NSStatusItem *statusItem;
#property (weak) IBOutlet NSWindow *window;
#property (weak) IBOutlet NSMenu *statusItemMenu;
#property (weak) IBOutlet NSMenuItem *toggleLoginLogoutMenuItem;
#property (weak) IBOutlet NSTextField *statusField;
#property (weak) IBOutlet NSTextField *progressField;
#property (weak) IBOutlet NSProgressIndicator *progressIndicator;
#property (assign) BOOL loggedIn;
- (IBAction)toggleLoginLogout:(id)sender;
#end
In the nib file, the delegate outlet of the statusItemMenu is set to the MDAppDelegate controller class. That assures that the MDAppDelegate class is in the responder chain and allow it to work with validating the menu items.
Then you could implement your .m like the following:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
_statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
_statusItem.menu = _statusItemMenu;
_statusItem.title = NSLocalizedString(#"NSStatusItem", #"");
[self updateLoggedInStatus];
}
- (void)updateLoggedInStatus {
[self.statusField setStringValue:(self.loggedIn ? #"Logged in" : #"Logged out")];
}
- (IBAction)toggleLoginLogout:(id)sender {
[self performSelector:#selector(finishFakeLoginLogout:)
withObject:nil afterDelay:2.0];
}
- (void)finishFakeLoginLogout:(id)sender {
self.loggedIn = !self.loggedIn;
[self updateLoggedInStatus];
}
- (void)menuNeedsUpdate:(NSMenu *)menu {
#if MD_DEBUG
NSLog(#"[%# %#]", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
#endif
}
- (BOOL)validateMenuItem:(NSMenuItem *)menuItem {
#if MD_DEBUG
NSLog(#"[%# %#]", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
#endif
SEL action = menuItem.action;
if (action == #selector(toggleLoginLogout:)) {
[menuItem setTitle:(self.loggedIn ? #"Logout" :#"Login")];
}
return YES;
}
Sample project: http://github.com/NSGod/NSStatusBarFinagler
You don't need to connect your menu item just try this..
NSMenuItem *menuItem = (NSMenuItem*) sender;
NSString *menuString = menuItem.title;
if ([menuString isEqualToString:#"Login"])
{
[menuItem setTitle:#"LogOut"];
}
NSMenuItem menuItem = (NSMenuItem) sender;
this line automatically collect the menu items in your app.

Delegate does not get called

I have a UIPageViewController which I setup in the viewDidLoad method of the RootViewController as follows:
[self addChildViewController:self.pageViewController];
[self.view addSubview:self.pageViewController.view];
The delegate pageViewControllerspineLocationForInterfaceOrientation is called successfully and I can set the spine accordingly.
However, I want to setup the PageViewController on a button click so I moved the code to the event handler of the button pressed event. Now the delegate is not called.
Any ideas how I can fix it?
It is some what complicated but can be achieved through the code below :
Step 1: Add below code to .h file of rootViewController.
#property (strong, nonatomic) IBOutlet UIButton *previousClick;
#property (strong, nonatomic) IBOutlet UIButton *nextClick;
Step 2: Connect them to the xib or storyboard which ever you use.
Step 3: Add two IBAction methods to .m file.
#pragma mark - IBAction Methods
- (IBAction)previousClick:(id)sender
{
[_modelController pageViewController:self.pageViewController viewControllerBeforeViewController:_dataViewController];
}
- (IBAction)nextClick:(id)sender
{
[_modelController pageViewController:self.pageViewController viewControllerAfterViewController:_dataViewController];
}
Step 4: You also need to put below lines too to .m file
#interface RootViewController ()
#property (readonly, strong, nonatomic) ModelController *modelController;
#property (readonly, strong, nonatomic) DataViewController *dataViewController;
#end
And synthesize them as below
#synthesize modelController = _modelController;
#synthesize dataViewController = _dataViewController;
Step 5: Last and final add below line to - (UIPageViewControllerSpineLocation)pageViewController:(UIPageViewController *)pageViewController spineLocationForInterfaceOrientation:(UIInterfaceOrientation)orientation method.
_dataViewController = currentViewController;
after the currentViewController's alloc init call.
If you find that the added buttons are hidden by the pageViewController just bring them to the front using the code below in side the -viewDidLoad method
[self.view bringSubviewToFront:self.previousClick];
[self.view bringSubviewToFront:self.nextClick];

SplitViewController UI layout

I'm trying to create a UI whereby I have a SplitView with the Details area containing a TabBarController. The TabBarController will show 3 different types of detail for the item selected in the RootViewController of the SplitView.
So far, I've got the TabBar showing the SPlitView by doing the following;
1) Created a new SplitView based app.
2) Created a new TabBar based app
3) Copy the .xib, .h and .m files for the FirstView and SecondView controllers from the TabBar app into the SplitView app.
4) Added the following to my application delegate header file;
#class RootViewController;
#class DetailViewController;
#class FirstViewController;
#class SecondViewController;
#interface SplitViewTemplateAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
UISplitViewController *splitViewController;
UITabBarController *tabBarController;
RootViewController *rootViewController;
DetailViewController *detailViewController;
FirstViewController *firstViewController;
SecondViewController *secondViewController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet UISplitViewController *splitViewController;
#property (nonatomic, retain) IBOutlet RootViewController *rootViewController;
#property (nonatomic, retain) IBOutlet DetailViewController *detailViewController;
#property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;
#property (nonatomic, retain) IBOutlet FirstViewController *firstViewController;
#property (nonatomic, retain) IBOutlet SecondViewController *secondViewController;
5) Opened up MainWindow.xib in IB and changed the class on the DetailsView to UITabController
6) Added the following code to my application delegate module file;
#import "FirstViewController.h"
#synthesize window, splitViewController, rootViewController, detailViewController, tabBarController, firstViewController, secondViewController;
-(void) makeTabBarController {
NSMutableArray *controllers = [NSMutableArray arrayWithArray:splitViewController.viewControllers];
int index = 0;
for (UIViewController *controller in splitViewController.viewControllers) {
if (index == 1) {
//NSLog(#"Index is: %#", index);
//NSLog(#"Controller name is: %#", controller.title);
UINavigationController *localNavController;
tabBarController = [[UITabBarController alloc] init];
NSMutableArray *localViewControllersArray = [[NSMutableArray alloc] initWithCapacity:2];
firstViewController = [[FirstViewController alloc] initWithNibName:#"FirstView" bundle:nil];
localNavController = [[UINavigationController alloc] initWithRootViewController:firstViewController];
localNavController.tabBarItem.title = #"First Tab";
[firstViewController release];
[localViewControllersArray addObject:localNavController];
[localNavController release]; // Retained by above array
secondViewController = [[SecondViewController alloc] initWithNibName:#"SecondView" bundle:nil];
localNavController = [[UINavigationController alloc] initWithRootViewController:secondViewController];
localNavController.tabBarItem.title = #"Second Tab";
[secondViewController release];
[localViewControllersArray addObject:localNavController];
[localNavController release]; // Retained by above array
tabBarController.viewControllers = localViewControllersArray;
[localViewControllersArray release]; // Retained thru above setter
//tabBarController.delegate = splitViewController;
[controllers replaceObjectAtIndex:index withObject:tabBarController];
}
index++;
}
splitViewController.viewControllers = controllers;
}
7) Added the following to the didFinishLaunchingWithOptions method;
[self makeTabBarController];
So now I get an out of the box SplitView with a tab bar controller on the right with two tabs in it. The tabs work for switching between the views.
A couple of things that I am now struggling with are;
The button to fire the Popover is missing, do I need to add this to each tab view?
How do I hook the RootViewController with the TabBarController so that details for the selected item is shown?
not sure if you're still looking for an answer for this. I ran into a very similar issue with the question about multiple detail views. In the end, I found and used this solution from the apple developer site:
SubstitutableDetailViewController
Their solution is very straightforward to implement and very understandable.
With regards to the second part of your question, you could have the TabBarController Delegate inform the view on the left hand side of the split view who the current detail view is. It could then use that information to provide updates to the proper view.