FAQ Database Discussion Community


Limiting number of threads

objective-c,multithreading,grand-central-dispatch
I need to download images through background threads, but limit the number of threads. Maximum thread number must be 5 and in each thread must be just one serial queue. For client-server using socket rocket library. The main trouble is that i don't need NSOperation pluses like canceling operations. Looking...

EXC BAD ACCESS in ABRecordCopyValue

ios,grand-central-dispatch,abaddressbook
I get EXC_BAD_ACCESS problem either while getting birthday or email for random people variable. I tried using the following code which fails when I run it using dispatch_async. ABAddressBook addressBook = ABAddressBookCreateWithOptions(NULL, error); CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook); CFIndex nPeople = ABAddressBookGetPersonCount(addressBook); int maxThreads = 8; int chunkSize = (int)(nPeople/maxThreads); for...

Why is asynchronous network testing difficult in Objective-C/Swift?

ios,swift,asynchronous,concurrency,grand-central-dispatch
So I'm learning more about how to test asynchronous code when I come across the following: As soon as a given test method completes, XCTest methods will consider a test to be finished and move onto the next test. That means that any asynchronous code from the previous test will...

Synchronous Dispatch Doesn't Work?

ios,swift,firebase,grand-central-dispatch
Maybe I'm not understanding the concept but shouldn't this second piece of code wait before the first one is done? dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> () in // do some task var myRef = self.userRef.childByAppendingPath(self.userRef.authData.uid) myRef.observeSingleEventOfType(.Value, withBlock: { snapshot in println("WE ARE IN HERE") firstName = snapshot.value["firstName"] as String! lastName...

Can you call dispatch_sync from a concurrent thread to itself without deadlocking?

ios,objective-c,multithreading,swift,grand-central-dispatch
I know you would deadlock by doing this on a serial queue, but I haven't found anything that mentions deadlocking by doing it on a concurrent queue. I just wanted to verify it wont deadlock (it doesn't seem like it would, as it would only block one of the threads...

In Swift, why GCD is not working with parse?

swift,parse.com,grand-central-dispatch
I have already asked this on In Swift, how to stop all the process until datas retrieved from parse.com in UICOLLECTIONVIEW. I couldn't retrieve the datas from parse.com before next function get executed. I don't know how to access asynchronous thread. I have declared main queue to be "first_fun()", so...

iOS Realm Update Object In Block

ios,objective-c,grand-central-dispatch,realm
I'm working on integrating Realm into an iOS app, and am beginning to write a class to handle all of my Realm stuff and was writing a convenience method to update any RLMObject dynamically. In their docs, updating an object is as simple as: - (void)someMethod { [self.realm beginWriteTransaction]; someObject.name...

what is the difference between DISPATCH_QUEUE_CONCURRENT and Global Concurrent Dispatch Queues

ios,multithreading,grand-central-dispatch
I read here in the apple documentation that for creating concurrent queues both DISPATCH_QUEUE_CONCURRENT and Global Concurrent Dispatch Queues can be used however I am uncertain as to what the difference between the two is. E.x. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ }); and dispatch_queue_t queue = dispatch_queue_create("custom",DISPATCH_QUEUE_CONCURRENT); dispatch_async(queue, ^{ }); I read...

Swift: can I add and subtract `dispatch_time_t` variables?

ios,swift,time,grand-central-dispatch
I need to do some time math in iOS, with Swift. I have to use dispatch_walltime. I hope that can be taken as axiomatic. Where time math is concerned, I think I'm likely to get the response "just use NSDate," but please take it on faith: I am bound to...

Does dispatch_async() and similar provide memory fences?

objective-c,grand-central-dispatch,memory-fences
When I run a block on any queue via dispatch_async or similar, does GCD provide thread fences around the block invocation? I would assume it does, but the documentation gives no hint one way or the other as far as I can tell.

Prevent loop from looping until inner loop writes to disk

ios,objective-c,grand-central-dispatch,nsdata
I have a nested for loop in where I call a getSnapShotData method many times and write this data to disk. I've noticed I get too much memory build up doing this and I run out of memory, so I thought this would be a good use case for using...

Stop execution of a GCD, when the ViewController is popped

ios,objective-c,grand-central-dispatch
I have a -[tableView reloadData] method in my app and to make the execution faster, I have called it in a GCD in the following method. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ [tableView reloadData]; }); But when I pop my viewController, the app crashes with this message [SecondViewController numberOfSectionsInTableView:]: message...

Using dispatch_write to write NSData to unique file in background under ARC

ios,automatic-ref-counting,grand-central-dispatch,nsdata
I am attempting to create a file with a unique name and write data to it in the background. mktemp says Whenever it is possible, mkstemp() should be used instead, since it does not have the race condition. Using mkstemp results in an open file descriptor, so dispatch_write seems to...

Objective-C - block loop from continuing until delegate method is called

objective-c,json,objective-c-blocks,grand-central-dispatch,nsurlconnectiondelegate
In each loop, I initialize a connector class with an id that is used to perform a JSON call. The problem is, is that this loop continues to iterate before the connectionDidFinishLoading delegate method of the connector class completes, parses the JSON as needed then uses a delegate method with...

IOS, Swift, No way to access main thread in NSURLSession

ios,swift,grand-central-dispatch,nsurlsession
I am creating an iOS app using swift. I would like to achieve some GET or POST HTTP request. I know that Alamofire exists but i want to create my own functions. What I have done : import Foundation class DatabaseRequest:NSObject{ class func GET(urlAsString:String, completion : (response:NSURLResponse, result:AnyObject?, error:String?)-> Void){...

dispatch_async doesn't go into loop

objective-c,synchronization,grand-central-dispatch
I need to fill in array. I have two methods. First of this create object that need to be added to array. I do it like this: __block NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:inputArray.count]; dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_sync(queue, ^{ dispatch_apply(inputArray.count,queue , ^(size_t index) { [array insertObject:[self getObject:[inputArray objectAtIndex:index]] atIndex:index];...

Performing segue taking up too much time

ios,objective-c,xcode6,grand-central-dispatch
I have a -[self performsSegueWithIdentifier:..] method in my app. It is called after I click the "GO" button in the keypad. Since an API is being called at that moment, it needs about 5 seconds to load the data. So, I put an -endEditing command after in the -buttonAction. I...

requestAccessForMediaType doesn't ask for permission

swift,avfoundation,grand-central-dispatch
I noticed that my app doesn't request permission to use the camera. After some experimentation I figured out that the piece of code used to check permission takes a very long time to complete. So I thought of letting that part of my viewdidload run on a serial queue (sync)....

swift: Grand-Central-Dispatch but code is executed on mainthread?

ios,grand-central-dispatch
Im importing data with an adressbookframework and storing the contacts within core data. The method is wrapped in GCD but the UI doesn't respond and all the code is executed on thread 1. What's wrong with my code? func importContacts(){ dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.value), 0)) { self.importContactsFromAdressbook() } } ...

Can thread be used analogously with queue, or do they mean separate things?

objective-c,multithreading,swift,concurrency,grand-central-dispatch
I was reading through this great tutorial when I came accross the following line (as background: we were learning how to use dispatch_apply to replace a for loop and concurrently download photos): Be aware that although you have code that will add the photos in a thread safe manner, the...

Does NSURLSession Take place in a separate thread?

ios,objective-c,grand-central-dispatch,nsurlsession
I was designing an app that uses NSURLSession and thinking about putting it in a different thread with Grand Central Dispatch, but if NSURLSession automatically does that in the background, I wouldn't have to use GCD then, correct? So in other words, does NSURLSession automatically use Grand Central Dispatch in...

Grand Central Dispatch alternative to using an NSTimer - invalidating multiple times

ios,objective-c,grand-central-dispatch,photosframework
I have an issue with a dispatch_source_t I'm trying to use. I'm wanting to use it to delay the processing of a PHChange for 5 seconds because a PHChange can happen multiple times in a short span. I'd appreciate any help offered. Essentially I want to cancel the prior dispatch_source_t...

Should I wrap dispatch_group_leave in an @synchronized block?

ios,objective-c,osx,grand-central-dispatch
Given the following code, is the @synchronized call un-required? I assume that dispatch_group_enter/leave is atomic but it's not listed as thread safe here https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/dispatch_group_leave.3.html and I'm suddenly worried I've been messing up all this time. // Imagine this is on its own queue already (possibly main, possibly not) dispatch_group_t group...

Dispatch group and NSNotification

objective-c,grand-central-dispatch,nsnotificationcenter,nsnotification
My issue is simple. I have 3 tasks, one is triggered by an NSNotification. How to I wait for all task to be completed before proceeding. So far, I tried using dispatch group but can't find a way to add the task triggered by NSNotification. (I tried adding the dispatch...

Why does dispatch_queue_create give an EXC_BAD_ACCESS error in Swift?

c++,swift,queue,port,grand-central-dispatch
I am porting some code from C++ to Swift that used Grand Central Dispatch, and I am finding a curious error with dispatch_queue_create seemingly not working at all. For instance, in my C++ base class header, I would declare dispatch_queue_t m_WorkQ; and in the initializer, put m_ResultQ = dispatch_queue_create("com.myapp.mHitsUpdateQueue", 0);...

Display multiple views serially using GCD

ios,objective-c,iphone,uiwebview,grand-central-dispatch
I have 4 tabs and all have UIWebView. I want that the first tab should load and displayed immediately without waiting for others to load. For which I did this in UITabBarController class: for(UIViewController * viewController in self.viewControllers){ if(![[NSUserDefaults standardUserDefaults]boolForKey:@"isSessionExpired"]) { if((int)[self.viewControllers indexOfObject:viewController] != 4) { viewController.tabBarItem.tag = (int)[[self viewControllers]...

how to make asynchronous request using concurrent queues?

ios,grand-central-dispatch
Can someone help me on how to send asynchronous request using concurrent queues. Most of the discussions does not look like it has got an answer. The following is the code that I've written. When my request is being fetched, my ui displays the activity indicator. Once the response is...

Use dispatch_async to analyze an array concurrently in Swift

ios,multithreading,swift,grand-central-dispatch,dispatch-async
I am trying to analyze a photo concurrently using a background thread from GCD. Here is the code I have written: dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_UTILITY.value), 0)) { for (var i = 0; i < 8; i++) { let color = self.photoAnalyzer.analyzeColors(imageStrips[i]) colorList.append(color) } } For clarification on the variable names, here are their...

How to run n async functions and be notified when they all complete?

ios,swift,grand-central-dispatch
I'm using Alamofire to execute a variable number of requests in a for loop which are all asynchronous. I need to find a way to be notified when all the requests complete (successfully or not) and to collect their results for processing. Is there a feature for this built in...

how to do cancel requests in GCD without operation queue

ios,objective-c,rest,grand-central-dispatch
I'm implementing an iOS app which make requests using REST service. And I want to cancel all the previous REST calls when I make a new call. Can I do it in the global queue in GCD without Operation Queue? Thanks

Objective C for loop delay

objective-c,for-loop,cocos2d-iphone,delay,grand-central-dispatch
I have a for loop that I want to add a delay between iterations. I have changed waitUntilDone to YES and get the same results. My array only has two numbers in it and both are called after the five seconds instead of: 0s - nothing 5s - Block called...

Run 3 methods one after each other

objective-c,xcode,grand-central-dispatch,nsurlsessiondatatask
I need to run 3 methods one after each other in a seperate thread that calls an api (NSURLSessionDataTask async). I have looked into dispatch groups but this seems to run method 1 and 2 at the same time and then runs method 3 when they finish: dispatch_group_t group =...

weak self in gcd in swift closure

swift,closures,grand-central-dispatch,weak-references
apiFunc(user: User.currentUser, start: 0, limit: Constants.numberOfItemInOnePage, success: { [weak self] (friends) -> Void in dispatch_async(dispatch_get_main_queue(), { [weak self] () -> Void in if let strongSelf = self { strongSelf.friendList = friends strongSelf.loading = false strongSelf.tableView.reloadData() } }) }, failure: nil) error Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1 happens...

Data is loading very slow using GCD

ios,objective-c,grand-central-dispatch
I have am trying to pull data from HealthKit, the data is being pulled correctly and with enough speed. I think there might be something wrong with the way I have GCD set up. Here is the code: - (void)loadGraphDataForType:(NSString *)type withDuration:(int)graphDuration { NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *interval...

Timer Not Repeating (Grand Central Dispatch)

ios,xcode,swift,grand-central-dispatch,nstimer
I'm trying to learn how to dispatch computations on a background thread and resultantly update the UI after. When I attempt this in an existing project with Google Maps, "background" followed by "main" is printed once. No more printing occurs, as if the timer does not repeat. Further, when I...

Does dispatch_group_wait allow cutting in line?

ios,osx,grand-central-dispatch
This question is about Grand Central Dispatch, and dispatch_group_wait() in particular. Assume a dispatch_group called group with 10 tasks in it waiting to be performed. Elsewhere I have a task that needs to wait for any tasks in group to finish before it executes. To make that happen, I use...

dispatch_group_t - EXC_BAD_INSTRUCTION

objective-c,grand-central-dispatch
This is my first time using dispatch_group_t and I'm making a simple mistake. dispatch_group_notify is getting called before any of the async calls are returning therefore before even the first dispatch_group_leave(group), which then throws a EXC_BAD_INSTRUCTION. However, I don't know why this is happening. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_group_t...

iOS8 Swift TableView LoadingOverlay Grand Central Dispatch

ios,swift,overlay,grand-central-dispatch
I'm writing an app where I've got multiple TableViews. If you click the cell from the first one, it opens a second one with specific parameters. For each one of them I parse some content from a website, which often takes some time. I want my users to know that...

GCD custom queue for synchronization

objective-c,synchronization,grand-central-dispatch
In Mike Ash's GCD article, he mentions: "Custom queues can be used as a synchronization mechanism in place of locks." Questions: 1) How does dispatch_barrier_async work differently from dispatch_async? Doesn't dispatch_async achieve the same function as dispatch_barrier_async synchronization wise? 2) Is custom queue the only option? Can't we use main...

'Realm accessed from incorrect thread' error in prepareForSegue; Swift

ios,multithreading,swift,grand-central-dispatch,realm
What am I doing wrong that would cause a 'Realm accessed from incorrect thread' error? 2015-03-14 06:59:54.962 MyApp[25646:1218284] *** Terminating app due to uncaught exception 'RLMException', reason: 'Realm accessed from incorrect thread' *** First throw call stack: ( 0 CoreFoundation 0x01961466 __exceptionPreprocess + 182 1 libobjc.A.dylib 0x01212a97 objc_exception_throw + 44...

How to call dispatch_block_t directly?

objective-c,osx,automatic-ref-counting,grand-central-dispatch
I am trying to update some code for XCode 6.1 / Yosemite. It's a bit weird because it's a macro, but essentially it looks like: dispatch_block_t blk = ^{ [[self globalEventsHandler] someMethod self]; }; if([NSThread isMainThread]) blk(); else dispatch_async(dispatch_get_main_queue(), blk); This is causing compilation problems. I have already set OS_OBJECT_USE_OBJC=0...

Calling dispatch_sync from a concurrent queue - does it block entirely?

ios,objective-c,multithreading,swift,grand-central-dispatch
Let's say I hypothetically call a dispatch_sync from a concurrent queue - does it block the entire queue or just that thread of execution?

iOS stop global queue from running

ios,xcode,grand-central-dispatch
Code: dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ [ServerAPI API_GetChatList:self withUserId:[self getUserIDFromUserDefaults] withScheduleId:strGroupId withType:@"group"]; dispatch_async(dispatch_get_main_queue(), ^{ [self performSelector:@selector(getChatList) withObject:nil afterDelay:10]; }); }); I used dispatch global queue to call a method for every 10 seconds.It is working fine.The problem is global queue is keep running in other controllers too.How do i stop this...

Concurrent processing on main queue during UITableView scroll

cocoa-touch,grand-central-dispatch
I have a stopwatch screen in my app. There is a main label indicating passing time every 100 milliseconds (updates constantly). Just below that label, in the same ViewController I have a UITableView. Whenever I'm scrolling the UITableView, the stopwatch labels stops updating. I've tried using Grand Central Dispatch as...

NSURLSessionDataTask and threading

ios,objective-c,grand-central-dispatch
I’m getting a JSON feed with NSURLSessionDataTask and populating an NSMutableArray that is inside a shared store which is a singleton. The NSMutableArray is accessible to the outside world through a getter that casts it as an NSArray. The getter calls a refresh method which polls the JSON feed and...

reusable multithread implementation in Sprite Kit

ios,objective-c,multithreading,sprite-kit,grand-central-dispatch
I am working on a Sprite Kit game and I need to do some multithreading to maintain the healthy fps. On update I call a function to create a lot of UIBezierPaths and merge them using a C++ static library. If I have more than 10 shapes the frame rate...

GCD, NSThread, and performSelector:onThread: issues

ios,objective-c,multithreading,grand-central-dispatch
I'm attempting to debug some iOS crash logs that contain the following error message: *** Terminating app due to uncaught exception 'NSDestinationInvalidException', reason: '*** -[SomeClass performSelector:onThread:withObject:waitUntilDone:modes:]: target thread exited while waiting for the perform The relevant section of the code is: - (void) runInvocationOnMyThread:(NSInvocation*)invocation { NSThread* currentThread = [NSThread currentThread];...

Delaying Code Execution on OSX 10.10

grand-central-dispatch,osx-yosemite,nsthread,mach,usleep
I've encountered a very strange issue that affects my code running only on OSX 10.10 systems. I've seen this anomaly occur on over 25 OSX 10.10 systems running my code, whereas the exact same code did not exhibit this behavior before upgrading (10.7). Furthermore, this issue is not 100% reproducible...

ios “has active assertions beyond permitted time:” crash with async task

ios,multithreading,nsurlconnection,grand-central-dispatch
I sometimes get the crash "myApp has active assertions beyond permitted time:" in my today widget. After some googling, I guess it is caused because I handle background task inappropriately. I use two type of background task. dispatch_async and NSURLConnection. I'm a newbie and I can't figure out which one...

Serial Dispatch Queue with Asynchronous Blocks

multithreading,cocoa,swift,asynchronous,grand-central-dispatch
Is there ever any reason to add blocks to a serial dispatch queue asynchronously as opposed to synchronously? As I understand it a serial dispatch queue only starts executing the next task in the queue once the preceding task has completed executing. If this is the case, I can't see...

How to parallelize many (100+) tasks without hitting global GCD limit?

ios,objective-c,multithreading,asynchronous,grand-central-dispatch
The problem: When lazy-loading a list of 100+ icons in the background, I hit the GCD thread limit (64 threads), which causes my app to freeze up with a semaphore_wait_trap on the main thread. I want to restructure my threading code to prevent this from happening, while still loading the...

Is it safe to use GCD to open a socket connection on iOS, even with a complex stack?

ios,sockets,grand-central-dispatch,nsoperationqueue
I have an iOS app with which I was previously using performSelectorInBackground to open a persistent socket connection. However, according to this answer, one should never use performSelectorInBackground. The alternative, GCD and NSOperationQueue, both appear to persist the full stack frame, including 4! separate context switches, when I pause my...

Does dispatch_after block the main thread?

ios,objective-c,multithreading,grand-central-dispatch,dispatch-async
I'm setting a timer so that after a second passes I reset a value for my keyboard extension. The problem is that I feel like the following call is stalling my UI: dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ [self resetDoubleTapBool]; }) Is there an asynchronous way of doing this, or...

Race conditions in iOS using GCD for UICollectionView

ios,objective-c,grand-central-dispatch
I am hoping that someone can help me out with this code and try to figure out the best way to optimize it so I don't have so many race conditions. Some things that I know are happening: Sometimes the collection view does not even show up Only some items...

Why are UI events not thread-safe in Swift/Objective-C?

ios,multithreading,grand-central-dispatch
So I'm beginning to learn the basics of Grand Central Dispatch and the whole concept of multithreading with iOS applications. Every tutorial will tell you that you must run UI events on the main thread, but I don't completely understand why. Here's a problem I came across yesterday, and finally...

WKWebView: trying to query javascript synchronously from the main thread

ios,ios8,grand-central-dispatch,semaphore,wkwebview
Is there any way to query the javascript synchronously from the main thread? Javascript is queried from the native code using an asynchronous function with a callback parameter to handle the response: func evaluateJavaScript(_ javaScriptString: String, completionHandler completionHandler: ((AnyObject!, NSError!) -> Void)?) Asynchronous behavior can usually be turned synchronous by...

How to use “loop” parallel processing by using GCD (grand central Dispatch )

c++,grand-central-dispatch
I have programmed C++ under visual studio environment. there to do parallel processing i used openMP but OS X isn't supporting for openMP so i like to move GCD Apple . By using GCD how do i optimise the following loop ( here i want to do the thing what...

How do I store one completion handler in a class so that all methods could use it?

objective-c,objective-c-blocks,grand-central-dispatch,nsurlsession
Supposing I have a class with class methods only and within a method I have two NSURLSessionDataTask / NSURLSessionUploadTask instances which have a completion handler like this: ^(NSData *responseData, NSURLResponse *response, NSError *error){ //here parsing the response etc. } which are 100% identical for both tasks. What's the best way...

GCD serial queue with NSTimer, dispatch_sync doesn't wait for the NSTimer to complete

ios,objective-c,multithreading,grand-central-dispatch,nstimer
I'm currently trying make a queueHandler that takes an object array as input for executing drive commands on a simple Double robot. I'm currently trying to use GCD in order to serially execute my functions, but when I'm using dispatch_sync on my queue in won't wait until the NSTimer has...

GCD Implementation not working with PARSE Query (Swift)

ios,swift,asynchronous,parse.com,grand-central-dispatch
I've looked all over Stack Overflow and other web resources on how to handle the async PARSE query and storing this data into an array. I then use this array to populate a table in another view controller. Code structure is as follows: AppController.swift: public var BuisnessNames = [NSString]()...

How to cancel GCD queue?

ios,grand-central-dispatch
I need to know the number of task not yet started on a serial GCD queue. The reason is that I want them to 'cancel', like this: if(!canceled) { ... do work } ...

Why putting “self” in the GCD blocks will cause a memory leak?

ios,block,grand-central-dispatch,autorelease,retain-cycle
I have read the great article write by benzado that using block will cause memory leak if we have a class variable retain the block itself, and the block retain "self", that cause a retain cycle. How do I avoid capturing self in blocks when implementing an API? But I...

Run operations in a group concurrently, but run then run batches of these operations serially

objective-c,grand-central-dispatch
Take these to enumeration loops. They enumerate an array of objects and save them. I want each of these to run concurrently, HOWEVER, I want to wait until all of the categoriesMainToSave return before starting on the categoriesSubToSave batch. // Save all the categories [categoriesMainToSave enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL...

iOS - API Synchronization

ios,swift,core-data,grand-central-dispatch,alamofire
I'm building a toy app in iOS where the user can: Create tasks, stored locally Those tasks will be synced to the server Create tasks in a web page They will be synced back to the app All of this using Core Data for persistence and Alamofire for networking, coded...