How do you safely lock a variable using GCD? - cocoa

I have an NSMutableArray I need to add objects to from multiple blocks I have dispatched. Is this an acceptable way to make sure that the array is safely being changed? These are already being dispatched from inside and NSOperation and running in the background. I was loading the data from within that thread serially but it was getting very slow to load a list of locations at once.
NSMutableArray *weatherObjects = [[NSMutableArray alloc] init];
ForecastDownloader *forecastDownloader = [[ForecastDownloader alloc] init];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t serialQueue;
serialQueue = dispatch_queue_create("us.mattshepherd.ForecasterSerialQueue", NULL);
for (NSDictionary *theLocation in self.weatherLocations) {
// Add a task to the group
dispatch_group_async(group, queue, ^{
NSLog(#"dispatching...");
int i = 0;
WeatherObject *weatherObject = [forecastDownloader getForecast:[theLocation objectForKey:#"lat"] lng:[theLocation objectForKey:#"lng"] weatherID:[[theLocation objectForKey:#"id"] intValue]];
}
if(!weatherObject){
//need to implement delegate method to show problem updating weather
NSLog(#"problem updating weather data");
}else{
NSLog(#"got weather for location...");
dispatch_sync(serialQueue, ^{
[weatherObjects addObject:weatherObject];
});
}
});
}
// wait on the group to block the current thread.
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
NSLog(#"finished getting weather for all locations...");
//we will now do something with the weatherObjects

That's not going to work because you're making a new lock each time, rather than using a single lock for the variable (analogy: imagine a locked door to a room. If everyone gets their own door with a lock, it hardly matters that they lock it, since everyone else will come in their own door).
You can either use a single NSLock for all iterations, or (basically equivalently) a single serial dispatch queue.

Related

Inject keyboard event into NSRunningApplication immediately after foregrounding it

I am trying to bring to foreground a NSRunningApplication* instance, and inject a keyboard event.
NSRunningApplication* app = ...;
[app activateWithOptions: 0];
inject_keystrokes();
... fails to inject keyboard events, but:
NSRunningApplication* app = ...;
[app activateWithOptions: 0];
dispatch_time_t _100ms = dispatch_time( DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC) );
dispatch_after(
_100ms,
dispatch_get_main_queue(),
^{ inject_keystrokes(); }
);
... succeeds.
I imagine it takes a certain amount of time for the window to render in the foreground, and maybe this happens on a separate thread, and this explains the injection failure.
However this is a very ugly solution. It relies on an arbitrary time interval.
It would be much cleaner to somehow wait for the window to complete foregrounding.
Is there any way of doing this?
PS inject_keystrokes() uses CGEventPost(kCGHIDEventTap, someCGEvent)
PPS Refs:
- Virtual keypress goes to wrong application
- Send NSEvent to background app
- http://advinprog.blogspot.com/2008/06/so-you-want-to-post-keyboard-event-in.html
Adding an observer for the KVO property isActive on NSRunningApplication works for me.
for (NSRunningApplication* ra in [[NSWorkspace sharedWorkspace] runningApplications])
{
if ([ra.bundleIdentifier isEqualToString:#"com.apple.TextEdit"])
{
[ra addObserver:self forKeyPath:#"isActive" options:0 context:ra];
[ra retain];
[ra activateWithOptions:0];
}
}
// ...
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context
{
if ([keyPath isEqualToString:#"isActive"])
{
NSRunningApplication* ra = (NSRunningApplication*) context;
[ra removeObserver:self forKeyPath:#"isActive"];
[ra release];
inject_keystrokes();
}
}
Note that I manually retain and then release the NSRunningApplication to keep its reference alive, since I'm not keeping it in a property or ivar. You have to be careful that the reference doesn't get dropped with the observer still attached.

cocoa: dispatch design pattern

-(void) test{
for(Person *person in persons){
__block CGPoint point;
dispatch_async(dispatch_get_main_queue(), ^{
point = [self.myview personToPoint:person];
});
usePoint(point); // take a long time to run
}
}
I need to run personToPoint() in the main queue to get the point, and usePoint() method doesn't need to run in main queue and take a long time to run. However, when running usePoint(point), point has not been assigned value because using dispatch_async. If using dispatch_sync method, the program will be blocked. the how can I using point after it has been assigned?
UPDATE:
how to implement the pattern of the following code:
-(void) test{
NSMutableArray *points = [NSMutableArray array];
for(Person *person in persons){
__block CGPoint point;
dispatch_async(dispatch_get_main_queue(), ^{
point = [self.myview personToPoint:person];
[points addObject:point];
});
}
usePoint(points); // take a long time to run
}
Something like the following would work. You might also put the entire for loop inside one dispatch_async() and let the main thread dispatch all the usePoint() functions at once.
-(void) test{
for(Person *person in persons){
dispatch_async(dispatch_get_main_queue(), ^{
CGPoint point = [self.myview personToPoint:person];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
usePoint(point); // take a long time to run
});
});
}
}
Solution for Updated question:
You use the same basic pattern as suggested above. That is you dispatch the stuff you need to do on the main thread to the main thread and then nest a dispatch back to a default work queue inside the main thread dispatch. Thus when the main thread finishes its work it will dispatch off the time consuming parts to be done elsewhere.
-(void) test{
dispatch_async(dispatch_get_main_queue(), ^{
NSMutableArray *points = [NSMutableArray array];
for (Person *person in persons){
CGPoint point = [self.myview personToPoint:person];
[points addObject:[NSValue valueWithCGPoint:point]];
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
usePoint(points); // take a long time to run
});
});
}
Note that there was an error in your code as you can't add CGPoint's to an NSArray since they are not objects. You have to wrap them in an NSValue and then unwrap them in usePoint(). I used an extension to NSValue that only works on iOS. On Mac OS X you'd need to replace this with [NSValue valueWithPoint:NSPointToCGPoint(point)].

how to update other contexts with changes from alternate threads

I have a mainContext that is used on the main thread. When the mainContext is created, I add an observer to the NotificationCenter for NSManagedObjectContextDidSaveNotification notifications.
If a new thread gets created and needs an NSManagedObjectContext, I create the context on the new thread and store some info for it. I save changes to the context on the new thread.
My notification handler gets called and merges changes for all contexts on their threads. I have a merge policy for each context in affect and I am merging changes on the appropriate threads.
I still randomly get "optimistic locking failure". Is there something I am missing?
- (void)contextChanged:(NSNotification *)notif
{
//gets called from the thread(where the context was) that made the changes
//iterate over all contexts and mergeChanges on their thread
NSLog(#"NotifContext %# %p", [notif object], [NSThread currentThread]);
//always check the main
if([notif object] != [self mainContext]){
NSLog(#"merge with main %#", [self mainContext]);
[[self mainContext] performSelectorOnMainThread:#selector(mergeChangesFromContextDidSaveNotification:) withObject:notif waitUntilDone:NO];
}
//check alternate cotexts and merge changes on their threads
NSDictionary *altContexts = [self.altContexts copy];
for(NSString *threadAddress in altContexts){
NSDictionary *info = [altContexts objectForKey:threadAddress];
NSManagedObjectContext *context = [info objectForKey:#"context"];
if(context != NULL && [notif object] != context){
NSLog(#"merge with %#", context);
NSThread *thread = [info objectForKey:#"thread"];
[context performSelector:#selector(mergeChangesFromContextDidSaveNotification:) onThread:thread withObject:notif waitUntilDone:NO];
}else{
NSLog(#"not with %#", context);
}
}
[altContexts release];
}
waitUntilDone:NO //should have been YES
I overlooked this. I meant to wait until it was done. Otherwise, the save happens (on thread 2), the notification gets dispatched, the contextChanged: handler gets triggered, the other contexts are told to merge changes on their thread (say thread 1), and thread 2 continues before the context on thread 1 actually gets to save.

High memory usage during CoreData import

I'm attempting to perform a fairly large CoreData import (around 25,000 rows) while still maintaining a fairly low memory footprint. I've read the documentation surrounding efficient importing of data and have endeavoured to implement everything suggested there (including setting things like my MOC's undoManager to nil).
Unfortunately, my applications memory usage still climbs to around 180MB when running the below code. Upon completion the application will sit at around the 180MB mark, regardless of the final NSAutoreleasePool drain call.
Running the application through Allocations shows that 95% of the memory usage is attributable to my [self.moc save:&error] call. What am I doing wrong here?
- (void)generateCache
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSUInteger count = 0, batchSize = 1000;
// SNIP SNIP
// Iterate over our directory structure
for(NSString *item in directoryStructure)
{
NSDictionary *info = [fm attributesOfItemAtPath:item error:nil];
FileRecord *record = (FileRecord *)[NSEntityDescription insertNewObjectForEntityForName:#"FileRecord" inManagedObjectContext:self.moc];
record.size = [NSNumber numberWithUnsignedLongLong:[info fileSize]];
record.path = item;
count ++;
if(count == batchSize)
{
NSError *error = nil;
if([self.moc save:&error])
{
NSLog(#"MOC saved down and reset");
[self.moc reset];
[pool drain];
pool = [[NSAutoreleasePool alloc] init];
count = 0;
}
}
}
// Perform any necessary last minute MOC saves
if (count != 0) {
[self.moc save:nil];
[self.moc reset];
}
// Drain our NSAutoreleasePool
[pool drain];
// Tell our main thread that we're done
if ([self respondsToSelector:#selector(completedCache)])
{
[self performSelectorOnMainThread:#selector(completedCache) withObject:nil waitUntilDone:NO];
}
}
Instead of dealing with auto-release pools, why not explicitly manage the life-cycle of your managed objects by creating them with NSManagedObject's initWithEntity:insertIntoManagedObjectContext:? You can safely release them after modifying the object's properties since a managed object context retains a newly inserted object -- till its saved to the persistent store.
Also, I should mention a couple of problems that I see with your code:
As someone mentioned above, you are not logging errors from the save: operation. You really should -- that may highlight some (possibly unrelated) problem.
If save: is successful, you really should not need to call reset. See this section in the core data guide.

NSThread with _NSAutoreleaseNoPool error

I have an method which save files to the internet, it works but just slow. Then I'd like to make the user interface more smooth, so I create an NSThread to handle the slow task.
I am seeing a list of errors like:
_NSAutoreleaseNoPool(): Object 0x18a140 of class NSCFString autoreleased with no pool in place - just leaking
Without NSThread, I call the method like:
[self save:self.savedImg];
And I used the following to use NSThread to call the method:
NSThread* thread1 = [[NSThread alloc] initWithTarget:self
selector:#selector(save:)
object:self.savedImg];
[thread1 start];
Thanks.
Well first of all, you are both creating a new thread for your saving code and then using NSUrlConnection asynchronously. NSUrlConnection in its own implementation would also spin-off another thread and call you back on your newly created thread, which mostly is not something you are trying to do. I assume you are just trying to make sure that your UI does not block while you are saving...
NSUrlConnection also has synchronous version which will block on your thread and it would be better to use that if you want to launch your own thread for doing things. The signature is
+ sendSynchronousRequest:returningResponse:error:
Then when you get the response back, you can call back into your UI thread. Something like below should work:
- (void) beginSaving {
// This is your UI thread. Call this API from your UI.
// Below spins of another thread for the selector "save"
[NSThread detachNewThreadSelector:#selector(save:) toTarget:self withObject:nil];
}
- (void) save {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// ... calculate your post request...
// Initialize your NSUrlResponse and NSError
NSUrlConnection *conn = [NSUrlConnection sendSyncronousRequest:postRequest:&response error:&error];
// Above statement blocks until you get the response, but you are in another thread so you
// are not blocking UI.
// I am assuming you have a delegate with selector saveCommitted to be called back on the
// UI thread.
if ( [delegate_ respondsToSelector:#selector(saveCommitted)] ) {
// Make sure you are calling back your UI on the UI thread as below:
[delegate_ performSelectorOnMainThread:#selector(saveCommitted) withObject:nil waitUntilDone:NO];
}
[pool release];
}
You need to mainly create an autorelease pool for the thread. Try changing your save method to be like this:
- (void) save:(id)arg {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//Existing code
[pool drain];
}
You will not you that the above does not call release on the NSAutoreleasePool. This is a special case. For NSAutoreleasePool drain is equivalent to release when running without GC, and converts to a hint to collector that it might be good point to run a collection.
You may need to create a run loop. I will add to Louis's solution:
BOOL done = NO;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSRunLoop currentRunLoop];
// Start the HTTP connection here. When it's completed,
// you could stop the run loop and then the thread will end.
do {
SInt32 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, YES);
if ((result == kCFRunLoopRunStopped) || (result == kCFRunLoopRunFinished)) {
done = YES;
}
} while (!done);
[pool release];
Within the thread, you need to create a new autorelease pool before you do anything else, otherwise the network operations will have issues as you saw.
I don't see any reason for you to use threads for this. Simply doing it asynchronously on the run loop should work without blocking the UI.
Trust in the run loop. It's always easier than threading, and is designed to provide the same result (a never-blocked UI).

Resources