NSArrayController rearrangeObjects error - cocoa

I have troubles with NSArrayController rearrangeObjects function - this function called from some background treads and sometimes App crashes with error: 'endUpdates called without a beginUpdates'.
How can i detect if arrayController is rearranging objects in current moment and add next rearrange to some like queue or cancel current rearranging and run new?
May be there is another solution for this problem?
Edit code added:
TableController implementation:
- (void)setContent{//perfoms on main thread
//making array of content and other functions for setting-up content of table
//...
//arrayController contains objects of MyNode class
//...
//end of setting up. Call rearrangeObjects
[arrayController rearrangeObjects];
}
- (void)updateItem:(MyNode *)sender WithValue:(id)someValue ForKey:(NSString *)key{
[sender setValue:someValue forKey:key];
[arrayController rearrangeObjects];//exception thrown here
}
MyNode implementation:
- (void)notifySelector:(NSNotification *)notify{
//Getted after some processing finished
id someValue = [notify.userInfo objectForKey:#"observedKey"];
[delegate updateItem:self WithValue:someValue ForKey:#"observedKey"];
}

Don't do that. AppKit (to which NSArrayController belongs) is not generally thread safe. Instead, use -performSelectorOnMainThread:... to update your UI (including NSArrayController). ALWAYS do updating on the main thread.

Joshua and Dan's solution is correct. It is highly likely that you are performing operations on your model object in a background thread, which then touches the array controller, and hence touches the table.
NSTableView itself is not threadsafe. Simply adding in a "beginUpdates/endUpdates" pair will just avoid the race condition for a bit. However, like Fin noted, it might be good to do the pair of updates for performance reasons, but it won't help with the crash.
To find the sources of the crash, add some assertions in your code on ![NSThread currentThread].mainThread -- particularly any places before you touch the array controller's content. This will help you isolate the problem. Or, subclass NSTableView and add the assertion in somewhere key, like overriding -numberOfRows (which is called frequently on changes), and calling super.
-corbin
AppKit/NSTableView

I solved this by adding this at the very start of my UI initialisation
[myTableView beginUpdates];
and then at the end after the persistant store has been loaded fully:
[myTableView endUpdates];
This also make the app startup a lot better since it does not constantly have to reload all loads from the MOC.

Related

NSOutlineView reloadItem: has no effect

I'm trying to release some strain on a view-based NSOutlineView for which I changed a single item property and which I initially reloaded just fine using [myOutlineView reloadData].
I tried [myOutlineView reloadItem: myOutlineViewItem] but it never calls - (NSView *)outlineView:(NSOutlineView *)ov viewForTableColumn:(NSTableColumn *)tableColumn item:(id)item and consequently the data is not updated.
-(void)reloadOutlineViewObject
{
//[myOutlineView reloadData]; //Reload data just fines but is ressource-hungry
NSLog(#"%d",[myOutlineView rowForItem:myOutlineViewItem]; //Making sure my object is an item of the outlineView, which it is !
[myOutlineView reloadItem:myOutlineViewItem];
}
Am I missing something here ?
UPDATE
As pointed out in the comments, my outlineView is view-based.
UPDATE 2
Trying out some stuffs made me realized that the object I am reloading is a second-level object (cf object tree) and calling reloadItem:firstLevelObject reloadChildren:YES does work.
Would it be possible that we can only call reloadItem: on first-level object ? That would be highly inefficient in my case (I only have one two level item and plenty of second level) !
nil ->firstLevelA ->secondLevel1
->secondLevel2
->firstLevelB ->secondLevel3
->secondLevel4
Gonna try to subclass NSOutlineView and rewrite reloadItem: in the mean time.
UPDATE 3
I took a look at NSOutlineView in Cocotron to get start and felt that the code I needed to write to overwrite reloadItem would be quiet heavy. Anyone to confirm ?
I encountered this same problem with a view-based outline view, where calling -reloadItem: seems to just not do anything. This definitely seems like a big bug, though the documentation doesn't explicitly say that reloadItem will reacquire the views for that row.
My workaround was to call NSTableView's -reloadDataForRowIndexes:columnIndexes: instead, which seems to work as expected, triggering a call to the -outlineView:viewForTableColumn:item: delegate method for just that item. You can get the row that needs to be reloaded by calling -rowForItem: and passing in the item you want to reload.
This really isn't a bug - it was something I had explicitly designed. My thought was that reloadItem (etc) should just reload the outline view item properties, not the table cell at that item, since it doesn't carry enough specific information on what to reload (such as what specific cell you might want reloaded). I had intended for people to use reloadDataForRowIndexes:columnIndexes: to reload a particular view based tableview cell; we usually don't provide cover methods when the base class can easily do the same thing with just a few lines of code.
However, having said that, I know multiple people have gotten confused about this, and most people expect it to reload the cell too.
Please log a bug requesting Apple to change this.
thanks,
-corbin
Apple seems to have "fixed" it.
WWDC 2016, presentation 203 "What's New in Cocoa" at 30:35 in the video:
"NSOutlineView
Reloads cell views associated with the 'item' when reloadItem() is called"
reloadItem: works only on macOS 10.12.
From release notes:
https://developer.apple.com/library/content/releasenotes/AppKit/RN-AppKit/
NSOutlineView will now reload the cell views associated with ‘item’
when [outlineView reloadItem:] is called. The method simply calls
[outlineView reloadDataForRowIndexes:columnIndexes:] passing the
particular row that is to be reloaded, and all the columns. For
compatibility, this will only work for applications that link against
the 10.12 SDK.
So, if you want to reload row on earlier systems, you should use -reloadDataForRowIndexes:columnIndexes:.
Something like that:
let index = outlineView.row(forItem: obj)
let rowIndex = IndexSet(integer: index)
let cols = IndexSet(0 ... outlineView.numberOfColumns)
outlineView.reloadData(forRowIndexes: rowIndex, columnIndexes: cols)

How to allow loadView to be sent to my NSViewController?

Having discovered that awakeFromNib is begin called multiple times, I tried to implement loadView in the following way to prevent (nib loading) initialization from repeatedly occurring, with:
- (void)loadView {
[self viewWillLoad];
[super loadView];
[self viewDidLoad];
}
Looks like a good trick to allowing certain arrays and properties to be set-up in viewWillLoad, but loadView absolutely won't be called.
Why?
I've done much research about this here and through google.
You're not receiving a loadView message because you have this VC and its view in the same nib, with the VC's view outlet set to the view. Since the VC already has a view, it has no reason to go load another one.
loadView is typically not called if you are using a nib (since view is already set). But the real question is why you're trying to fight the view loading process this way. If awakeFromNib is being called multiple times, that suggests you have multiple instances of this class. Each will get a call to awakeFromNib (that is expected behavior). If this is surprising, you should dig into why you have multiple instances. But you shouldn't try to subvert the view-loading mechanism like this.

Proper way of showing a NSWindow as sheet

Function NSBeginAlertSheet(...) has all the events I need to have especially the didDismiss: callback, but I really need to be able to do the same sheet action with any window I want, so I discovered this notification:
NSWindowDidOrderOffScreenAndFinishAnimatingNotification
Which is posted whenever a sheet is closed AND done with animations
now, my question is can I use that? Or is there a better way?
I use ARC and I load the windows from .xib using NSWindowController.
Overall what I need is to show a window as sheet and catch all events.
What's wrong with
- (void)beginSheet:(NSWindow *)sheet modalForWindow:(NSWindow *)docWindow modalDelegate:(id)modalDelegate didEndSelector:(SEL)didEndSelector contextInfo:(void *)contextInfo
This calls the optional didEndSelector which should look like this:
- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo;
This is all in the NSApplication documentation. There are two methods for ending the sheet:
- (void)endSheet:(NSWindow *)sheet returnCode:(NSInteger)returnCode
- (void)endSheet:(NSWindow *)sheet
So you could just do whatever you wanted to right before calling endSheet: or you could in the sheetDidEnd: method.
Edit:
Here is an example project showing that after calling [window orderOut:self] then animation is finished and you can do what you'd like.
NSWindowDidEndSheetNotification It is posted whenever a sheet is finished animating out.
Starting with 10.9, the correct way is to call beginSheet:completionHandler: on a NSWindow object.
This method has the advantage, that the completion handler is a block, so it can keep all the objects alive that are required as long as the sheet is still displayed and once the sheet is done and the block has been executed, the block itself is released and thus all objects it was keeping alive are as well.
To make sure a block keeps objects alive, use the objects within that block or if there is no way to use them in a meaningful fashion, put all of them into a NSMutableArray and within the block call removeAllObjects on that array; this requires the block to keep the array alive and the array keeps the rest alive -> memory management made easy.

Cannot Save in a Document-Based Application

I created new Document-Based-App.
I implemented dataOfType in subclass of NSDocument
- (NSData*) dataOfType:(NSString *)typeName error:(NSError *__autoreleasing *)outError
{
return [NSKeyedArchiver archivedDataWithRootObject:bcmwc.bindingsController.arrangedObjects];
}
in xib http://i.minus.com/iH2Rj9v5oOhTn.png
When I click "Save" from menu nothing's gonna happen, any errors in console.
I set a breakpoint in dataOfType, and when I clicked "Save", application didn't stop.
Any suggestions?
EDIT
I think it may be connected with fact I use custom NSWindowController, and custom xib.
I made a test when I load custom xib, everything is fine dataOfType method is invoked etc..
Should I connect in some way my custom xib (window) with subclass of NSDocument?
It looks like your Save menu item is connected properly, so let's concentrate on the code (+1 for having posted it in the first place).
You do nothing in your code to ensure -archivedDataWithRootObject: returns valid data or set an error if it doesn't. My best guess (because you haven't provided nearly enough detail to do anything but guess) is that you're returning nil because your call to -archivedDataWithRootObject: is doing the same. Check to see if you get valid data and set the outError if not.
Why would you get nil? Perhaps one or more of the objects in the object graph created by archiving your array controller's -arrangedObjects array isn't <NSCoding> compliant. This is likely the case if your array controller holds objects of a custom class you created rather than a standard Property List container.
Read the Archives and Serializations Programming Guide (in particular, the Encoding and Decoding Objects section) to learn how to make your custom class <NSCoding> compliant so that it knows how to serialize itself (write itself into a byte stream suitable for NSKeyedArchiver, etc. and create an instance of itself from such a byte stream).
Also, you really need to learn to use the debugger. You're groping around in a dark cave with lots of pitfalls and no flashlight without it. Try setting a breakpoint in methods you expect to be called. If they're not called, you can check outlets/actions, etc. If they are, you can step through each line and make sure everything is executing as you expected. If you write a little more verbose code, you can more easily inspect the results when paused in the debugger. Two lines in your case will help you more than one:
- (NSData*) dataOfType:(NSString *)typeName error:(NSError *__autoreleasing *)outError
{
NSData * myData = [NSKeyedArchiver archivedDataWithRootObject:bcmwc.bindingsController.arrangedObjects];
// You should be handling nil (setting a descriptive error) here if (!myData)...
return data; // breakpoint here; you should now see myData is likely nil
}

How to use NSWindowDidExposeNotification

I am trying to update another windows when the one becomes visible. So I found the NSWindowDidExposeNotification and tried to work with it, so I wrote in my awakeFromNib:
// MyClass.m
- (void)awakeFromNib {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:#selector(mentionsWindowDidExpose:)
name:NSWindowDidExposeNotification
object:nil];
}
and implemented the method
// MyClass.h
- (void)mentionsWindowDidExpose:(id)sender;
// MyClass.m
- (void)mentionsWindowDidExpose:(id)sender {
NSLog(#"test");
}
But it never gets called which is odd. What do I do wrong here?
Generally speaking, you would set up your controller as the window's delegate in order to receive these notifications, like so:
// MyClass.m
- (void)awakeFromNib {
// note: this step can also be done in IB by dragging a connection
// from the window's "delegate" property to your `MyClass` object
[window setDelegate:self];
}
- (void)windowDidExpose:(NSNotification *)notification {
NSLog(#"test");
}
Although, after reading here and here, windowDidExpose may not be your best bet. I would recommend trying the windowDidBecomeKey delegate method instead. That one is posted whenever your window gains "focus" (starts responding to user input) which may be the right time to show your second window.
Update: (in response to comments)
Apple's documentation (quoted below) indicates that NSWindowDidExposeNotification is only valid for nonretained windows, which, according to the posts that I linked above, are quite uncommon.
NSWindowDidExposeNotification
Posted whenever a portion of a nonretained NSWindow object is exposed, whether by being ordered in front of other windows or by other windows being removed from in front of it.
The notification object is the NSWindow object that has been exposed. The userInfo dictionary contains ... the rectangle that has been exposed.
On a higher level, NSNotification objects are simply packages of data that get passed around between Cocoa classes and NSNotificationCenter objects. NSNotificationCenter objects are controllers that manage these packages of data and send them out to observers as required. There is usually no need to trap notifications directly. You can simply use KVC/KVO or pre-defined delegates in your classes and Cocoa handles all of the dirty details behind the scenes.
See Notification Programming Topics and Key Value Coding Programming Guide if you want to know more.

Resources