I want to add a undo manager to a coredata backed iphone application. When the user tries to add a new object (by tapping on + button) I load a new modal viewcontroller and start a new undo group in viewDidLoad.
When the user presses Cancel button, I want to rollback the changes in cancelAction callback.
Queries:
Is it possible to start a nested Undo group and persist it through event loop and collate all the changes done in one single undo group? Right now, when I call beginUndoGrouping in cancelAction, I get a missing beginUndoGrouping exception.
What is the significance of groupsByEvent API for NSUndoManager? Do I require to set it to NO to persist an undo group through event loop?
What needs to be done in saveAction callback to make changes permanent (apart from calling save on mangedObjectContext)? How do I tell Undo Manager to stop tracking the changes?
Error Message:
* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '_endUndoGroupRemovingIfEmpty:: NSUndoManager 0x75415f0 is in invalid state, endUndoGrouping called with no matching begin
Sample Code:
// RootViewController.m
- (void) addAction {
// Load Modal View Controller to add new object
}
// AddViewController.m
- (void) viewDidLoad {
// Start nested undo group
[self.managedObjectContext processPendingChanges];
[self.managedObjectContext.undoManager beginUndoGrouping];
[self createModel];
}
- (void) cancelAction {
// Revert all changes
[self.managedObjectContext processPendingChanges];
[self.managedObjectContext.undoManager endUndoGrouping];
[self.managedObjectContext.undoManager undoNestedGroup];
...
}
- (void) saveAction {
// Save changes
}
Beginning with your specific questions - Yes, you can manually define the bounds of an undo operation using beginUndoGrouping and endUndoGrouping.
In this case, the undo operation should work whether or not groupsByEvent is set. This is because all the undo groups that are generated by the event loop are nested under your main open undo grouping started with beginUndoGrouping, and as long as you call undoNestedGroup directly after you call endUndoGrouping, it should work. If you are not using the event loop undo groupings, don't worry about it and set it to NO.
To make your changes permanent, close the undo group with endUndoGrouping and call save on your context. The processPendingChanges calls are not needed, and may cause issues in nested groups. If you want clear the undo operations, call removeAllActions on your undomanager after endUndoGrouping - this guarantees the changes will never be un-did.
Use breakpoints/nslog to make sure your begin/end calls are one for one.
If you want your cancel action to be like an 'undo button', you'll have to do the following:
Move beginUndoGrouping to viewWillAppear
Call endUndoGrouping in viewWillDisappear
re-open undo grouping at the end of your cancel action
re-open undo grouping at the end of your save action
Otherwise, if you leave it as is, make sure you close the dialog in your save and cancel actions, to avoid possibility of endUndoGrouping being called multiple times.
If you have any questions, please comment and I'll update.
Good luck!
Related
I do a remove action through RxJava2 that causes a refresh on my local cache like this:
override fun removeExperience(experienceId: String, placeId: String): Completable {
return from(placesApi.deleteExperience(experienceId, placeId))
.andThen(from(refreshPlace(placeId))
.flatMapCompletable { Completable.complete() }
)
}
so whenever the remove action is done (Completable is complete), a refresh is triggered. The problem is, sometimes this remove action takes long enough for users to just leave the screen, and then the andThen action is never executed cause there is no subscribers anymore, and thus the information on the screen is not up to date anymore.
Is there a way to enforce this action to take place?
Does this logic continue working when user open the same screen again? If so, then you only need to finish subscription from(placesApi.deleteExperience(experienceId, placeId)) on lifecycle events. The easiest way is to add the whole subscription removeExperience() to Disposable or CompositeDisposable and then trigger its .dispose() or .clear() on view stop or destroy events.
.dispose() - doesn't allow to use the same subscription stored.
.clear() - allows re-subscription without creating the new
subscription instance
In my app I use two contexts: app delegate main context and a private context.
The private context is set as follows:
var privateContext: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
privateContext.persistentStoreCoordinator = context.persistentStoreCoordinator
I also set an observer on the private context to trigger a save via main context:
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyView.managedObjectContextDidSave(_:)), name: NSManagedObjectContextDidSaveNotification, object: self.privateContext)
I trigger a data download with a callback to the current ViewController. During the download, I process all objects in:
privateContext.performBlock {
// process objects
....
// now save
if self.privateContext.hasChanges {
privateDataManager.save()
}
}
The save in the private context, triggers the observer and this code gets invoked:
dispatch_async(AppUtils.GlobalMainQueue, {
self.context.mergeChangesFromContextDidSaveNotification(notification)
})
The problem is that every now and then, not all changes get persisted. Cannot say when or why - when I debug it it always works...
How do I know I have a problem? Well, I compare object count before and after the download. To add more 'colour':
Every download of data adds some new records. The app then selects which records are out-of-date and marks them for deletion (sets a flag on a record). It then saves them (new and 'to be deleted') in the private context. The 'save' triggers a 'merge into primary context' notification.
In theory, this notification triggers the 'merge' in a synchronous manner.
After the merge, assuming it does happen in-order, there is data reload - this reload only loads records that do not have the 'deleted' flag set.
The problem I am having is that the 'merge' does not seem to always happen before I reload (that's the only way I can explain this).
My question, assuming my analysis is correct, is how to force the merge to happen before the reload? Does the notification not happen in a synchronous manner?
I guess I could always save the private context and instead of triggering the notification, simply create a notification object using private context and force trigger the merge. But I would like to understand why the above code does not work as expected.
The main source on which I based my code can be found here.
I'm making an iOS 6 program which downloads JSON data from a website and displays it in a table view. I added a pull to refresh method witch works fine. I can go in the settings view controller (secondViewController) and change the address, everything works. Then, I use the pull to refresh method and my tableView is reloaded. But if I reload 3 times AFTER changing the address, my app crashes. I get this error :
*** Terminating app due to uncaught exception 'NSRangeException',
reason: '*** -[__NSArrayM objectAtIndex:]: index 10 beyond bounds for empty array'
*** First throw call stack:
(0x1ca1012 0x10dee7e 0x1c430b4 0x3084 0xdd8fb 0xdd9cf 0xc61bb 0xd6b4b 0x732dd 0x10f26b0 0x229dfc0 0x229233c 0x2292150 0x22100bc 0x2211227 0x22bb333 0x22bb75f 0x1c60376 0x1c5fe06 0x1c47a82 0x1c46f44 0x1c46e1b 0x1bfb7e3 0x1bfb668 0x22ffc 0x1fbd 0x1ee5)
libc++abi.dylib: terminate called throwing an exception
What am I doing wrong ? And how can I fix that problem ? Thanks for your help !
The key design consideration that leaps out is that your retreiveData method is clearly updating the model (the citiesArray) asynchronously, which means that any interaction with the tableview while this is taking place may fail. You should never asynchronously update the actual citiesArray itself. The update to that array should happen in the main queue.
You should change retrieveData to not touch the existing citiesArray, but rather create and return a new array, and then, in the code you dispatch back to the main queue, only then replace the existing citiesArray and call reloadData, something like:
- (void)refresh:(UIRefreshControl *)refreshControl {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSArray *newCitiesArray = [self retreiveData];
dispatch_async(dispatch_get_main_queue(), ^{
if (newCitiesArray) {
// you presumably only want to reload the data if `retrieveData` was successful
citiesArray = newCitiesArray
[myTableView reloadData];
}
[refreshControl endRefreshing];
});
});
}
Clearly, this will involve some changes to retrieveData, too, but hopefully that's self explanatory. If not, update your question with that code, and we can make further suggestions. But we really shouldn't need to go there, as I suspect you understand the change that needs to take place there.
There are other, more subtle issues you might want to tackle, too, such as thinking about whether you really want to use a global queue, which is concurrent (e.g. if you hit refresh while the previous refresh going, do you really want two queries going on concurrently with your server ... because you dispatch the updates back to the main queue you won't crash, but it's inefficient, you're not guaranteed the order that they'll complete, etc.). You might also want to use NSOperationQueue in which you can write code to permit the cancellation of previous requests, etc.
But all of this is a little complicated and is of secondary concern to your main issue, the crashing. Refactoring the retrieveData code to ensure you don't touch citiesArray, itself, as outlined above, should address that.
I have an app where I want to save the current state of a project before every change so that undo and redo will be able to step back and forth within those states. When I make a change the code to save the position is:
if(!undoManager){
undoManager = [[NSUndoManager alloc] init];
}
[[undoManager prepareWithInvocationTarget:self] replaceSelf:currentState];
And my undo/redo functions:
-(void)undo{
if(undoManager){
[undoManager disableUndoRegistration];
[undoManager undo];
[undoManager enableUndoRegistration];
}
}
-(void)redo{
if(undoManager){
[undoManager disableUndoRegistration];
[undoManager redo];
[undoManager enableUndoRegistration];
}
}
The replace self function just takes the project state property and distributes the information so that the state is restored.
Undo works perfect, i can perform 5 steps and then hit undo 5 times to rewind to the start, but redo does nothing at all! Shouldn't invoking redo cause it to hit my selector with the last object that was undone? What am I misunderstanding here?
I got this working, in the replaceSelf function that was being called by the undo/redo, I added this code:
[undoManager registerUndoWithTarget:self selector:#selector(replaceSelf:) object:ps];
Where ps is the current project state before the undo/redo is done.
This got it working for me!
I have the following code:
[self.view bringSubviewToFront:loggingIn];
[self loginWithUsername:user Password:pw];
This is inside an IBAction method for a button press. The button stays highlighted until the user is logged in (this could take several seconds) and THEN the view appears. How come the view isn't appearing before the login method is called?
John's answer would work, but it has to do with the Run Loop than blocking threads. Basically, whenever your app receives an event such as a button getting clicked, your handler gets run in the main thread. Any changes you make to the UI happen after your handler finishes. This lets Cocoa optimize the graphics updates by analyzing/performing them together.
Run Loop:
Event -> Your Handler Code -> System Updates UI
So you need to let your handler code finish in order to let the system start updating the UI - before invoking your loginWithUsername:Password: [sic] method. Scheduling a timer will bump it to the next iteration of the run loop (the timer going off becomes the "event" that triggers the next loop). So,
Run Loop (2 iterations):
Mouse Click -> Your Handler Code (reorder views) -> System reorders views
Timer Fires -> Your Handler Code (trigger login) -> Any addl UI updates
So do something like this:
- (void) buttonHandler: (id)sender {
[self.view bringSubviewToFront:loggingIn];
[self performSelector: #selector(performLogin)
withObject: [NSArray arrayWithObjects:user, pw, nil]
afterDelay: 0];
}
- (void) performLogin: (NSArray *)args {
[self loginWithUsername:[args objectAtIndex:0] Password:[args objectAtIndex:1]];
}
It doesn't have to be an array. You could also pack your username and password in a dictionary and use that as your argument instead.
The first call runs in a different thread which is blocked by the second line. Try delaying the second call by .1 seconds or so by using the:
- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay
method of NSObject. Since you are using two arguments you will need to either pass both as a single object or use instance variables.