Why is NSCollectionView not loading in Objective-C? - objective-c

I am learning about NSCollectionView compositional layout on macOS (12.4, Xcode 13.4). In the Swift version of this app everything works as expected, yet when converting it to Objective-C, while I get everything to compile, the app loads as blank.
I checked the outlets in the nib file (dataSource and delegate from Collection View to File's Owner), checked the creation of a reusable item (I build it through a custom nib). The error I get in the console when the app launches is as follows:
2022-07-21 15:26:25.817911+0200 Cocoa Pr L68 ObjC[14203:1414415] *** Assertion failure in -[_NSCollectionViewCore _dequeueReusableViewOfKind:withIdentifier:forIndexPath:viewCategory:], UICollectionView.m:6488
2022-07-21 15:26:25.818378+0200 Cocoa Pr L68 ObjC[14203:1414415] could not dequeue an item of kind: NSCollectionElementKindItem with identifier _NS:8 - must register a nib or a class for the identifier, or name a nib or class to match the identifier
Browsing the docs, I learned that NSCollectionView doesn't have a dequeueReusable kind of method like Table Views in iOS have so the first error is not clear to me. The second is even stranger because I've actually register a class for the identifier:
#import "CollectionViewController.h"
#import "CollectionViewItem.h"
#interface CollectionViewController ()
#property (weak) IBOutlet NSCollectionView *collectionView;
#end
#implementation CollectionViewController
#synthesize collectionView;
- (void)viewDidLoad {
[super viewDidLoad];
CollectionViewItem *collectionViewItem = [[CollectionViewItem alloc] init];
[collectionView registerClass:[NSCollectionViewItem class] forItemWithIdentifier:collectionViewItem.identifier];
[collectionView setCollectionViewLayout:self.listLayout];
}
The listLayout method is defined afterwards in the same file. All NSCollectionViewDataSource methods are properly defined as in the Swift version, for reference:
- (NSInteger)numberOfSectionsInCollectionView:(NSCollectionView *)collectionView {
return 3;
}
- (NSInteger)collectionView:(NSCollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 20;
}
- (NSCollectionViewItem *)collectionView:(NSCollectionView *)collectionView itemForRepresentedObjectAtIndexPath:(NSIndexPath *)indexPath {
NSCollectionViewItem *item = [collectionView makeItemWithIdentifier:collectionView.identifier forIndexPath:indexPath];
[item.textField setStringValue:[NSString stringWithFormat:#"%ld, %ld", indexPath.section, indexPath.item]];
return item;
}
The NSCollectionViewItem class is thus defined:
#import "CollectionViewItem.h"
#implementation CollectionViewItem
- (instancetype)init
{
self = [super init];
if (self) {
self.identifier = #"CollectionViewItemReuseIdentifier";
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
}
#end
I wonder what piece of the puzzle is missing as these errors, while apparently clear, seem to point to something that I have implemented. Have I implemented it wrong? Or not completely?
I would be very grateful to anyone shedding some light on all this.
Thank you

The registered class should be CollectionViewItem instead of NSCollectionViewItem. Change
[collectionView registerClass:[NSCollectionViewItem class] forItemWithIdentifier:collectionViewItem.identifier];
to
[collectionView registerClass:[CollectionViewItem class] forItemWithIdentifier:collectionViewItem.identifier];
It's in the error could not load the nibName: NSCollectionViewItem, but I'm so used to NS that I didn't notice.

Related

Swift 3 - superclass method is executing instead of its override counterpart

How can I override the ObjC methods, runThisMethod and controller:didChangeObject:, from the ViewControllerA class so that the app executes the counterparts from the Swift subclass, ViewControllerC, instead? In the code below, [ViewControllerA runThisMethod(someParameter)] will execute when the app detects a change in fetchedResultsController (via [ViewControllerA controller:didChangeObject:]. Can somebody help me see what I'm missing?
Main.swift
let vc = ViewControllerC.init()
self.myNavigationController?.pushViewController(vc, animated: true)
ViewControllerA.h
#interface ViewControllerA : UIViewController <NSFetchedResultsControllerDelegate>
#property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController;
- (void)setUpFetchedResultsController;
- (void)runThisMethod:(SomeParameterClass *)someParameter;
#end
ViewControllerA.m
#implementation ViewControllerA
- (void)setUpFetchedResultsController
{
// build fetch "request" here
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:[[MYCoreDataManager sharedCoreDataManager] managedObjectContext] sectionNameKeyPath:nil cacheName:nil];
self.fetchedResultsController.delegate = self;
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)someParameter atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
[self runThisMethod:someParameter]
}
- (void)runThisMethod:(SomeParameterClass *)someParameter
{
NSLog(#"This method will execute")
}
#end
ViewControllerB.h
#interface ViewControllerB : ViewControllerA
// declare a bunch of properties
#end
ViewControllerB.m
#implementation ViewControllerB
- (void)viewWillAppear:(BOOL)animated {
[self setUpFetchedResultsController];
}
#end
ViewControllerC.swift
class ViewControllerC: ViewControllerB {
override func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange someParameter: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
// this function won't run
self.runThisMethod(someParameter)
}
override func runThisMethod(someParameter){
// this function won't run
}
}
When I set up a sample project with the code as you've mentioned (and set up a bridging header file which imports in ViewControllerB.h) the overridden runThisMethod on ViewControllerC executes correctly. This is with Xcode 8.2.1. So everything appears to work as it should with the set up you mention.
Could you perhaps upload a sample project showing the behaviour that you mention so that we can take a look? My suspicion is that something is not set up correctly somewhere ...
One thing you might not be doing (since you've only provided part of the code) is overriding NSFetchedResultsController's didChangeObject delegate method in ViewControllerC.
Turns out the problem was in the predicate of my fetchedResultsController property. The predicate had a parameter that will causing fetchResultsController to always be nil when performing the fetch. Thus, the delegate method, controller:didChangeObject: was not being triggered.

How to use NSCollectionViewItem without subclassing it?

I am writing a very simple macOS application that I'd like to show a few images in a collection view. I don't need any special behavior for how they are displayed. The docs for NSCollectionViewItem say:
The default implementation of this class supports the creation of a simple item that displays a single image or string.
That is what I want. However, I can't find any information on how to create a default NSCollectionViewItem.
The documentation for NSCollectionView states:
Every data source object is required to implement the following methods:
collectionView:numberOfItemsInSection:
collectionView:itemForRepresentedObjectAtIndexPath:
The second method above returns an NSCollectionViewItem. From reading examples I gather that the traditional way of creating an NSCollectionViewItem in this case is to call:
NSCollectionViewItem* newCollectionViewItem = [imageCollectionView makeItemWithIdentifier:<some identifier>
forIndexPath:indexPath];
The problem is that I don't understand what <some identifier> should be. I don't have a nib that contains an NSCollectionViewItem because I'm not subclassing it or customizing it in any way. I've tried adding the following to my data source:
- (void)awakeFromNib
{
[imageCollectionView registerClass:[NSCollectionViewItem class]
forItemWithIdentifier:#"Image"];
}
where imageCollectionView is the NSCollectionView in question. And then in my - (NSCollectionViewItem *)collectionView:itemForRepresentedObjectAtIndexPath: method, I call:
NSCollectionViewItem* newCollectionViewItem = [imageCollectionView makeItemWithIdentifier:#"Image"
forIndexPath:indexPath];
But this throws an exception and prints this to the console:
2016-12-19 17:51:27.463 MyApp[28177:3926764] -[NSNib _initWithNibNamed:bundle:options:] could not load the nibName: NSCollectionViewItem in bundle (null).
followed by a stack trace.
So how do I go about creating and using an NSCollectionViewItem that isn't subclassed or modified in any way?
Here is a very simple example which uses a Nib for the item's prototype:
#interface ViewController()
#property (weak) IBOutlet NSCollectionView *collectionView;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSNib *theNib = [[NSNib alloc] initWithNibNamed:#"Item" bundle:nil];
[self.collectionView registerNib:theNib forItemWithIdentifier:#"item"];
}
#pragma mark NSCollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(NSCollectionView *)inCollectionView {
return 1;
}
- (NSInteger)collectionView:(NSCollectionView *)inCollectionView numberOfItemsInSection:(NSInteger)inSection {
return 10;
}
- (NSCollectionViewItem *)collectionView:(NSCollectionView *)inCollectionView itemForRepresentedObjectAtIndexPath:(NSIndexPath *)inIndexPath {
NSCollectionViewItem *theItem = [inCollectionView makeItemWithIdentifier:#"item" forIndexPath:inIndexPath];
NSTextField *theLabel = (NSTextField *)theItem.view;
theLabel.stringValue = [NSString stringWithFormat:#"%d.%d", (int)inIndexPath.section, (int)inIndexPath.item];
return theItem;
}
#end
The NIB contains just a NSCollectionViewItem with a text field as view.
Addendum:
I think you should create a NSCollectionViewItem.xib for the registerClass variant. A view controller will search for a NIB with its class name, if you doesn't create its view manually in loadView. Thus, you can't use plain NSCollectionViewItem without a NIB for registering a class, because of makeItemWithIdentifier:forIndexPath: will access the view of the item.
I found a way to set up NSCollectionView without needing to add a .xib file.
The trick was inheriting from NSCollectionViewItem and using that subclass for -[NSCollectionView registerClass:forItemWithIdentifier:].
#import "ViewController.h"
#interface MyViewItem : NSCollectionViewItem
#end
#implementation MyViewItem {
}
- (instancetype)initWithNibName:(NSNibName)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nil bundle:nil];
NSButton *button = [[NSButton alloc] initWithFrame:NSZeroRect];
[button setTitle:#"Button"];
[self setView:button];
return self;
}
#end
#implementation ViewController {
IBOutlet NSCollectionView *_collectionView;
}
- (void)viewDidLoad {
[super viewDidLoad];
[_collectionView registerClass:[MyViewItem class]
forItemWithIdentifier:#"item"];
[_collectionView setDataSource:self];
}
- (NSInteger)collectionView:(NSCollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 10;
}
- (NSCollectionViewItem *)collectionView:(NSCollectionView *)collectionView itemForRepresentedObjectAtIndexPath:(NSIndexPath *)indexPath {
return [_collectionView makeItemWithIdentifier:#"item" forIndexPath:indexPath];
}
#end

NSTabView blocking file-drop events active on underlying Window.

I have successfully implemented a file-drop functionality in my app. The Application window has a few NSTabView objects where dropping on them does not work. Anywhere else in the window the file-drop works fine.
I have tried to make the app delegate a delegate for the NSTabView, but this did not help.
Anyone have a setup for the NSTabView not to filter out the drop-actions so the whole window can be transparent to the file-drop actions ?
For a more generic solution than olekeh's I made it IB friendly so you can hook it up to any object that complies with the NSDraggingDestination protocol.
#import <Cocoa/Cocoa.h>
#interface DropFilesView : NSView
#property (nullable, assign) IBOutlet id<NSDraggingDestination> dropDelegate;
#end
#implementation DropFilesView
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
}
-(void) awakeFromNib {
[self registerForDraggedTypes:
[NSArray arrayWithObjects:NSFilenamesPboardType,
(NSString *)kPasteboardTypeFileURLPromise,kUTTypeData, NSURLPboardType, nil]]; //kUTTypeData
[super awakeFromNib];
}
-(NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender{
return [self.dropDelegate draggingEntered:sender];
}
- (BOOL)performDragOperation:(id < NSDraggingInfo >)sender {
return [self.dropDelegate performDragOperation:sender];
}
#end
I found the solution to this !! - I am posting it here for others who might need.
The NSTabView object has for each of its tabs an NSTabViwItem.
Under each of those, there is a regular NSView - that I subclassed with the following code: - The code assumes that you already have "draggingEntered" and "performDragOperation" in your AppDelegate as this class just forwards these messages to the app delegate. You will also need to put the declarations for those methods in you AppDelegate.h
// DropFilesView.h
#import <Cocoa/Cocoa.h>
#import "AppDelegate.h"
#interface DropFilesView : NSView
#end
and the implementation:
// DropFilesView.m
#import "DropFilesView.h"
#implementation DropFilesView
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
}
-(void) awakeFromNib {
[self registerForDraggedTypes:
[NSArray arrayWithObjects:NSFilenamesPboardType,
(NSString *)kPasteboardTypeFileURLPromise,kUTTypeData, NSURLPboardType, nil]]; //kUTTypeData
[super awakeFromNib];
}
-(NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender
{
AppDelegate* del = [AppDelegate sharedAppDelegate];
return [del draggingEntered:sender];
}
- (BOOL)performDragOperation:(id < NSDraggingInfo >)sender {
AppDelegate* del = [AppDelegate sharedAppDelegate];
return [del performDragOperation:sender];
}
#end
In Interfacebuilder, I set the new class for all the NSView objects covering areas where drop does not work, to this new one.
A similar approach can be used for NSImageView and the WebView classes. However, for the last one, do not use [super awakeFromNib] to prevent the default drag-and drop handling for the web view object.

Pressing a button on a custom keyboard is resulting in "Unrecognized selector being sent to instance error"

I know there are plenty of other questions addressing the same problem, but since I'm using a custom keyboard, I thought my problem would be slightly different.
This is the specific error:
-[EquationTextField element1Pressed:]: unrecognized selector sent to instance 0x4b68ee0
2012-01-02 12:23:44.630 rowQuiz[20975:207] Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[EquationTextField element1Pressed:]: unrecognized selector sent to instance 0x4b68ee0'
I have a view controller, quizController. Inside quizController is a custom view, textField (added through interface builder).
When textField is tapped, another custom view, formulaKeyboard, pops up as its keyboard. When a button on the keyboard is pressed, method element1Pressed: is called, and the error described above appears.
Some other questions say that there must be a problem with the retain count, so I tried retaining and releasing quizController in the app delegate, which didn't solve the problem.
It is also possible that I hooked up something incorrectly in Interface Builder; For the custom keyboard, File's owner and the main view are set to class elementKeyboard. For quizController, File's owner is set to quizController and hooked up to it's view.
Below is the code of the textField's class.
EquationTextField.h
#import <UIKit/UIKit.h>
#import "FormulaKeyboard.h"
#interface EquationTextField : UIView <KeyInput> {
FormulaKeyboard *keyboard;
NSString *lastElement;
}
#property (readwrite, retain) UIView *inputView;
#end
EquationTextField.m
- (id)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
if (self) {
self.userInteractionEnabled = YES;
[self addGestureRecognizer:
[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(becomeFirstResponder)]];
NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:#"FormulaKeyboard" owner:self options:nil];
for (id object in bundle) {
if ([object isKindOfClass:[FormulaKeyboard class]])
keyboard = (FormulaKeyboard *)object;
}
self.inputView = keyboard;
keyboard.delegate = self;
}
return self;
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
#pragma mark -- KeyInput Protocol Methods
- (void)addElement:(NSString *)elementName {
}
- (void)addCharge:(NSString *)chargeIncrease {
}
- (void) addState:(NSString *)stateName {
}
- (void)deleteCharacter {
}
- (void)dealloc
{
[super dealloc];
}
formulaKeyboard.h
#import <UIKit/UIKit.h>
#protocol KeyInput <UITextInputTraits>
- (void) addElement:(NSString*) elementName;
- (void) addCharge:(NSString*) chargeIncrease;
- (void) addState:(NSString*) stateName;
- (void) deleteCharacter;
#end
#interface FormulaKeyboard : UIView {
id <KeyInput> delegate;
}
#property (nonatomic, retain) id <KeyInput> delegate;
-(IBAction) element1Pressed:(id)sender;
-(IBAction) element2Pressed:(id)sender;
-(IBAction) element3Pressed:(id)sender;
-(IBAction) element4Pressed:(id)sender;
-(IBAction) element5Pressed:(id)sender;
-(IBAction) element6Pressed:(id)sender;
-(IBAction) chargePlusPressed:(id)sender;
-(IBAction) chargeMinusPressed:(id)sender;
-(IBAction) solidSatePressed:(id)sender;
-(IBAction) liquidStatePressed:(id)sender;
-(IBAction) gasStatePressed:(id)sender;
#end
formulaKeyboard.m
- (IBAction)element1Pressed:(id)sender {
[delegate addElement:#"Na"];
}
- (void)element2Pressed:(id)sender {
[delegate addElement:#"N"];
}
- (void)element3Pressed:(id)sender {
[delegate addElement:#"O"];
}
- (void)element4Pressed:(id)sender {
}
- (void)element5Pressed:(id)sender {
}
- (void)element6Pressed:(id)sender {
}
appDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
quizController = [[QuizController alloc] initWithNibName:#"QuizController" bundle:nil];
[self.window addSubview:quizController.view];
[self.window makeKeyAndVisible];
return YES;
}
- (void)dealloc
{
[_window release];
[quizController release];
[super dealloc];
}
The action of the keyboard's buttons are pointing to the wrong place. You've probably got them wired to File's Owner inside the FormulaKeyboard nib when they should be wired to the FormulaKeyboard object you're creating inside the nib.
NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:#"FormulaKeyboard" owner:self options:nil];
That's being called from EquationTextField, so self would be your instance of EquationTextField. If you're keyboard's targets are pointing there, that's why you get the unrecognized selector exception.
What's happening here is a method called element1Pressed: is being sent to an instance of EquationTextField. You need to actually add the method to the class for it to work. Right now, it's sending the message to the field class, but there's no matching method, so it's throwing an error.
Also, I can't be completely sure about this, since you haven't posted the whole code and/or NIB info, but it seems that you may be going about this the wrong way. You should be using a view controller to handle everything, rather than a custom text field class. I notice that you haven't posted any code for the QuizController class. Once you do so, I may be able to give you more advice.
EDIT: Now that you've posted more code, I think I see the problem. You want the FormulaKeyboard instance to receive the event, but the event is linked to the EquationTextField instance instead. Make sure you wire it to an instance of FormulaKeyboard instead.
On the other hand, it seems that you may not have an instance of FormulaKeyboard in the NIB at all. Add an NSLog after keyboard = (FormulaKeyboard *)object to test if keyboard is ever actually assigned a value. If the NSLog doesn't fire, double-check that you've actually added an instance of FormulaKeyboard to the NIB.

NSTableView binding problem

I have only just started with XCode (v3.2.2) and Interface Builder and have run into a problem.
Here is what I have done:
I have made a class to be the datasource of a NSTableView:
#interface TimeObjectsDS : NSControl {
IBOutlet NSTableView * idTableView;
NSMutableArray * timeObjects;
}
#property (assign) NSMutableArray * timeObjects;
#property (assign) NSTableView * idTableView;
- (id) init;
- (void) dealloc;
- (void) addTimeObject: (TimeObj *)timeObject;
// NSTableViewDataSource Protocol functions
- (int)numberOfRowsInTableView:(NSTableView *)tableView;
- (id)tableView:(NSTableView *)tableView
objectValueForTableColumn:(NSTableColumn *)tableColumn row:
(int)row;
#implementation TimeObjectsDS
#synthesize timeObjects;
#synthesize idTableView;
-(id) init {
if (self = [super init]) {
self.timeObjects = [[NSMutableArray alloc] init];
TimeObj *timeObject = [[TimeObj alloc] init];
[timeObject setProjectId:11];
[timeObject setDescription:#"Heja"];
[timeObject setRegDate:#"20100331"];
[timeObject setTimeSum:20.0];
[timeObjects addObject:timeObject];
[timeObject release];
[idTableView reloadData];
}
return self;
}
- (void) dealloc {
[idTableView release];
[timeObjects release];
[super dealloc];
}
// Functions
- (void) addTimeObject: (TimeObj *)timeObject {
[self.timeObjects addObject:timeObject];
[idTableView reloadData];
}
// NSTableViewDataSource Protocol functions
- (int) numberOfRowsInTableView:(NSTableView *)tableView {
return [self.timeObjects count];
}
- (id) tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row {
return [[timeObjects objectAtIndex:row] description];
}
#end
I have then bound my NSTableView in the View to this datasource like so:
alt text http://www.og-entertainment.com/tmp/ib_datasource_bindings_big.png
I have also bound the View NSTableView to the Controller idTableView variable in Interface Builder seen above
In the init function I add a element to the mutable array. This is displayed correctly in the NSTableView when I run the application. However when I add another element to the array (of same type as in init) and try to call [idTableView reloadData] on the View nothing happens.
In fact the Controller idTableView is null. When printing the variable with NSLog(#"idTableView: %#", idTableView) I get "idTableView: (null)"
Im runing out of ideas how to fix this. Any ideas to what I could do to fix the binding?
If your tableview outlet in your controller is null, then you haven't connected it in Interface Builder. Your screenshot above shows a connection to TimeObjectsDS, but that doesn't mean a lot - is that the instance that you are calling reloadData from? It is possible that you have more than one instance of this class, for example.
That's just one possibility. Without more code, it's not feasible to list many more.
Incidentally, in MVC it's considered a bad thing to connect a model object directly to a view. You may just be using the terminology incorrectly.