FAQ Database Discussion Community


Is it ok to override completionBlock property of NSOperation with different parameter types?

objective-c,cocoa,objective-c-blocks,nsoperation
Marcus Zarra's "Core Data" (2nd edition) book lists an example where in an NSOperation subclass he overrides the completionBlock property: @property (copy) void (^completionBlock)(void) NS_AVAILABLE(10_6, 4_0); with typedef void (^ExportCompletionBlock)(NSData *jsonData, NSError *error); @property (nonatomic, copy) ExportCompletionBlock completionBlock; which in Xcode 6 under 10.10 results in the following warnings: ‘atomic’...

Clarifications needed for a crash using NSArray, blocks and Manual Reference Counting

objective-c,memory-management,objective-c-blocks
I need some clarifications on a crash I'm encountering using NSArray, blocks and Manual Reference Counting. My goal is to store blocks on a collection (NSArray in this case) in order to reuse them in the future. I've setup a small sample to replicate the issue. In particular, I have...

I'm having trouble with my attempt of objective-c block equivalent in swift

objective-c,swift,objective-c-blocks,swift-closures
Here is the objective-c code: options.onPan = ^(MDCPanState *state){ if (state.thresholdRatio == 1.f && state.direction == MDCSwipeDirectionLeft) { NSLog(@"Let go now to delete the photo!"); } }; Swift: var options = MDCSwipeToChooseViewOptions() options.delegate = self options.likedText = "Keep" options.likedColor = UIColor.blueColor() options.nopeText = "Delete" options.onPan = { (state: MDCPanState) in...

Undefined selector with Objective-C runtime - blocks

ios,objective-c,iphone,objective-c-blocks,objective-c-runtime
I'm trying to create a function where multiple times I do the same thing. I've deceided to go with a block this time. However after writing following code: - (BOOL)readyForProcessing { void (^notDeclaredError)(id) = ^(id missingObject) { NSString *missingObjectName = NSStringFromSelector(@selector(missingObject)); NSString *errorDescription = [NSString stringWithFormat:@"You need to provide %@...

Retain Cycles for Blocks Inside of Blocks

ios,objective-c,objective-c-blocks
Do I have to continuously declare weak references to break retain cycles for blocks inside of blocks? __weak typeof(self) weakSelf = self; [self setMyBlock:^(id obj, NSUInteger idx, BOOL *stop) { typeof(self) strongSelf = weakSelf; [strongSelf doSomething]; [strongSelf setMyBlock:^(id obj, NSUInteger idx, BOOL *stop) { //do I need to create another...

Objective-C: Animations in Blocks

ios,objective-c,animation,objective-c-blocks
I have a UIImageView sliderPump which I move from right to left side of the screen infinite times by calling two methods one after another: -(void)pumpGoesRight { if (slide) { [UIView animateWithDuration:0.8 animations:^ { [sliderPump setFrame:CGRectMake(sliderPump.frame.origin.x+235, sliderPump.frame.origin.y, sliderPump.frame.size.width, sliderPump.frame.size.height)]; } completion:^(BOOL finished) { [self pumpGoesLeft]; }]; } else return; }...

iOS Block Design: Nested Blocks With Return Values?

ios,objective-c,objective-c-blocks
I have a delegate callback method that needs to return data(Ex NSArray) to the caller. I can get this data from another block call. Can anyone please help me with a design to use blocks in this case. I came up with something like this but not sure if this...

typedef in cocoa blocks

objective-c,cocoa,objective-c-blocks
I have a simple Blocks and typedef doubt. Consider the following codes, I've some typedef and two methods, second one is commented out. My doubt is regarding the first one. Should I use this one? Any issues or something that may arise in future? typedef void (^MySuccessBlock)(MyServiceResponse *response); typedef void...

Objective c block in a block

ios,objective-c,iphone,objective-c-blocks
Lot of blocks here! I am trying to use blocks to perform an operation on each record present in a dictionary. I created a weak reference of the strongRecordBlock and used that to call itself in the strongRecordBlock. It all worked fine until I introduced my actual operation (DataManager addRecord)...

Block completion handler reference is nil after completing background fetch

ios,objective-c,objective-c-blocks,background-process
I am trying to implement a background fetch of an RSS Feed using performFetchWithCompletionHandler, but when I want to call the completion handler it's nil. Am I missing a way to retain my reference to self.completionHandler? Am I declaring self.completionHandler correctly? in app delegate: //background fetch new RSS Feeds -(void)application:(UIApplication...

How to call instance methods inside a block?

ios,objective-c-blocks
I want to call instance methods inside a block. Here is the method that I am working with, [self.someVariable addBoundaryTimeObserverForTimes:timeArray queue:NULL usingBlock:^{ [self myInstanceMethod]; }]; But I am not able to reference self from inside this block. What should I do? EDIT: I am sorry that I posted this question...

Blocks in Swift shows error “Missing argument for parameter #2 in call” [closed]

objective-c,swift,objective-c-blocks
I'm now using Jonas Gessner's JGActionSheet with Swift in my project, and the sample was written by Objective-C, when I tried to convert the block to Swift, Xcode shows the error "Missing argument for parameter #2 in call", here is the code I written and the screenshot: Objective-C Sample JGActionSheet...

Objective-c: How to make multiple async service calls and block until they are all complete

objective-c,asynchronous,objective-c-blocks
I have a senario that requires me to make multiple call to a web api. The following is an example. getDataAsync:(NSDictionary *)dictionary withCompletion: (void (^)(NSDictionary*))completion { __block int counter = n; // the number of async blocks __block NSMutableDictionary *output = [[NSMutableDictionary alloc] init]; void (^returnBlock)(void) = ^{ counter--; if(counter...

NSOperationQueue gets complete notification before completing tasks

ios,objective-c,objective-c-blocks,nsoperation,nsoperationqueue
I am using NSOperation subclass in my app which will do following 4 tasks in a single operation, i wanted all these 4 tasks to run on background thread so I wrapped up into single NSOperation class, so that I can easily either pause or cancel it Tasks long time...

Objective-C callback block for BASS FX [closed]

ios,objective-c,objective-c-blocks,bass
I'm trying to use the audio library BASS in my application. I'm trying to use a method which triggers a callback when it detects a beat in the music. This is my current code: void* (^myBlock)(DWORD, double, void *) = ^(DWORD handle, double time, void *user) { return nil; };...

Confusion regarding blocks in ios

ios,objective-c-blocks
I have a bit of confusion regarding blocks. Say for example I have a block with completion BOOL: -(void) addNewSubGoalToLocalDatabaseAndParse:(CompletionBlock )cb { SubGoal* subGoalToAdd = [SubGoal new]; subGoalToAdd.name = subGoalName; subGoalToAdd.parentGoal = goal; Score* scoreToAdd = [Score new]; scoreToAdd.score = 0; scoreToAdd.subgoal = subGoalToAdd; [subGoalToAdd pinInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {...

Retain loop in a block

ios,objective-c,sprite-kit,objective-c-blocks,retain-cycle
I'm trying to get variables and properties in self in a block for actions to complete, but, if I reference self or a global variable in self when self is the object running the block, it warns me of a retain loop. Here's what I'm doing: I'm adding actions to...

How do I declare a block that returns a UIView?

ios,objective-c,objective-c-blocks
I keep trying to create a block that will return a UIView after it fetches it from the background. I got the fetch from the background part, but I am having trouble setting up the block. This code works, but I want a block that can be called from another...

block callbacks — when original object is deallocated

ios,objective-c,objective-c-blocks
I'm calling my DatabaseManager to save an object created in a viewController like so: [DatabaseManager addUniqueObject:fooChild key:[fooParent fooChildKey] toObject:self.foo callback:^(BOOL succeeded, NSError *error) { if (error) { [[UIApplication sharedApplication] endBackgroundTask:self.sendBackgroundTaskId]; return; } [self.tableView reloadData]; [self scrollToBottomAnimated:YES]; } [[UIApplication sharedApplication] endBackgroundTask:self.sendBackgroundTaskId]; }]; addUniqueObject is a class method in my DatabaseManager (I'm...

MKDirections calculateETAWithCompletionHandler: in background state

ios,objective-c,mapkit,objective-c-blocks
I have an app which monitors significant location changes. Upon receiving a new calculation I want to calculate the duration from the current location to a specified location. To calculate the duration I use calculateETAWithCompletionHandler: from the MKDirections class. Everything works as expected as long as the app is in...

How can I insert objects into an array in order of NSDate?

ios,cocoa-touch,swift,uiimageview,objective-c-blocks
I have a method that loads images that are used in a gallery for users profiles. The images are loaded in descending order using an "updatedPhotoAt" column in my DB. The purpose of the "updatedPhotoAt" column is to allow users to set a default image. This column is only ever...

iOS: UIBackgroundFetchResult completion handler inside of block

ios,objective-c,objective-c-blocks
Could use a little help here, as my understanding of blocks and completion handlers is very limited. I'm trying to implement background fetching in iOS while following along with this tutorial and changing things out as necessary: http://www.appcoda.com/ios7-background-fetch-programming/ I've implemented the necessary precursors to get background fetch enabled and have...

RACSignal combineLatest: cannot reduce

objective-c,objective-c-blocks,reactive-cocoa
I have a horrible compile problem while trying to reduce a couple of signals. RACSignal* contactIdentifierSignal = RACObserve(self, contactIdentifier); RACSignal* displayNameSignal = RACObserve(self, displayName); RACSignal* mappedThing = [RACSignal combineLatest:@[contactIdentifierSignal, displayNameSignal] reduce:^id(NSString* identifierValue, NSString* displayNameValue){ return @([identifierValue length] > 0 && [displayNameValue length] > 0); }]; The error that I get...

invoking block in array with parameters

ios,arrays,objective-c-blocks
I've seen the answer about invoking a block that is stored in an array, but I can't get it to work with parameters. I store the array an a part of an object, then when it's in a method, I want to invoke it, however, I need parameters. Also, is...

Why is this NSString null in a FireBase query block?

ios,objective-c,firebase,objective-c-blocks,nsmutabledictionary
I can't figure out why this string is null inside the FQuery block. My app keeps crashing when I build the dailyLog MutableDictionary at the user key; NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"MMMM dd, YYYY"]; NSString *userID = [[self.userProfile objectForKey:@"userID"] copy]; self.logFirebase = [[Firebase alloc] initWithUrl:@"https://urlName.firebaseio.com/DailyLog"]; [[[self.logFirebase queryOrderedByPriority]...

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...

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...

Method that returns block

ios,objective-c,cocoa-touch,objective-c-blocks
I wrote a method that can be used with a dot notation, using block tricks - (RaginiDBQuery *(^)(id object))where; This method can be called using a dot notation since basically it doesn't receive any parameters, (it does, but by using the block returned) So I can call it like so:...

How can I wait for delegate to complete before returning completion handler in method?

ios,xcode,delegates,objective-c-blocks,quickblox
I have a method which performs an action. - (void)mutualDeleteDialog:(QBChatDialog *)dialog success:(void (^) ())successBlock failure:(void (^)(NSError *))failureBlock { QBChatMessage *deleteMessage = [self generateDeleteDialogMessage:dialog]; [self sendMessage:deleteMessage success:^{ [QBChat deleteDialogWithID:dialog.ID delegate:self]; } failure:^(NSError *error) { failureBlock(error); }]; The deleteDialogWithID method calls a third party service and calls a delegate method when complete....

iOS(Objective-C). Application crash when getting block from array

ios,objective-c,memory-management,objective-c-blocks
Have a question about blocks in objective-c. For example I have a list of actions. I'm initializing an array of blocks: self.actions = @[ ^() { [self showObject:self.object_1]; }, ^() { [self showObject:self.object_2]; }, ^() { [self showObject:self.object_3]; } ]; And calling them when some row is pressed: - (void)pressedRowAtIndex:(NSInteger)index...

Is it correct to use local variable name “self” in blocks?

ios,objective-c-blocks,self
I`ve found that construction __strong typeof(self)self = weakSelf. It allows remove NSAssert macro self catching, but I am in doubt is it right to use it in that way? __weak typeof(self)weakSelf = self; self.signupBlock = ^{ __strong typeof(self)self = weakSelf; NSLog (@"%d", self.property) NSAssert((self.property > 5), @"Some message"); } Pls...

objective-c using blocks with recursion

ios,objective-c-blocks
I am coding an iphone app. And when I used blocks with recursion in Objective-C, I got a warning message of Capturing addImageToUploadEntity strongly in this block is likely to lead to a retain cycle. I created a block called addImageToUploadEntity is used to call an async function [self.submissionEntity addImageData:...

Is a __block variable assignment thread-safe to read immediately after the block?

ios,objective-c,synchronization,thread-safety,objective-c-blocks
__block NSHTTPURLResponse *httpResponse; dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error) httpResponse = (NSHTTPURLResponse *)response; } dispatch_semaphore_signal(semaphore); }]; [task resume]; dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); Is it safe to read httpResponse after this? The semaphore waits for the block to compete execution. If...

Unrecognized selector sent to instance when assigning a block property

ios,objective-c,objective-c-blocks
I have an app that may require the user to authenticate during navigation. If this is the case, I'd like the login event to return a callback back to the operation that requested the login event, for it to know that the login was either successful or not. For example,...

Can Swift return value from an async Void-returning block?

swift,return,closures,firebase,objective-c-blocks
I want to create a function to check if user_id is already in my database. class func checkIfUserExsits(uid:String) -> Bool { userRef.childByAppendingPath(uid).observeSingleEventOfType(.Value, withBlock: { (snapShot: FDataSnapshot!) -> Void in if snapShot.value is NSNull { return false } else { return true } }) } However, observeSingleEventOfType is a API provided...

Background performFetchWithCompletionHandler using Blocks causes crash

ios,objective-c,objective-c-blocks,background-process
I have an app that successfully fetches and displays RSS Feeds that I'd like to add background fetch. I receive: Thread 1 EXC_BAD_ACCESS (code=1, Address=0x10) where indicated below. In app delegate: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //setup background fetch [application setMinimumBackgroundFetchInterval: UIApplicationBackgroundFetchIntervalMinimum]; return YES; } //background fetch new RSS...

Confusion over how I should use weakSelf in blocks

ios,objective-c,parse.com,objective-c-blocks
I have a lot of blocks in my code. I have a process for initialising a user upon login, I am using Parse.com as my backend: PFQuery *messageBankQuery = [PFQuery queryWithClassName:@"messageBank"]; [messageBankQuery whereKey:@"username" equalTo:[PFUser currentUser].username]; [messageBankQuery getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) { if(!error){ [self setupUserWithMessageBank:object]; }//end no error if else{ NSLog:(@"error");...

BAD ACCESS after block within a block is called (iOS)

ios,firebase,objective-c-blocks,exc-bad-access
I have a block where I am checking a user's status property from firebase. If the status property is 'free' I want to return from the block, otherwise I want to search for another user and check their status and do so until a 'free' user has been found: void(...

Do methods called from within a block need to use weakSelf?

objective-c,objective-c-blocks,retain-cycle
If the code inside a block calls a method, will a retain cycle exist if that method references self? In other words, does all code downstream of a block need to use the weakSelf/strongSelf pattern? For example: __weak __typeof__(self) weakSelf = self; Myblock block = ^{ [weakSelf doSomething]; }; ....

Error return a NSString inside a block

objective-c,objective-c-blocks
I'm trying to declare a method and return two values BOOL, NSString for that I'm doing: typedef void(^myCompletion2)(BOOL, *NSString); The problem with this code is that this command return the warning message: type specifier missing, defaults to 'int' How to solve this problem?...

Objective-C can you use fast enumeration in place of “for (i = 0; i < X; i++)”

objective-c,objective-c-blocks,fast-enumeration
Let's say I've got a basic integer iteration like so: NSInteger rowCount = self.rowCount; for (int i = 0; i < rowCount; i++) { // stuff! } Is there a way to implement this using fast enumeration blocks? I could certainly create an array of integers 0 - self.RowCount, but...

Replacing Delegates with Blocks

ios,objective-c,objective-c-blocks
I have recently started learning Objective C and came across Blocks/Closures. They look much like Annonymous inner classes in Java to me. I have read somewhere that Blocks can be used to replace Delegates. This confuses me as in case of Delegates you signal a method when a specific task...

Scribble uncovering bug in block use I don't understand

xcode,osx,debugging,memory,objective-c-blocks
I have a bug which I have uncovered by enabling Scribble in Xcode, fixing the bug is not an issue, it isn't implemented in the best way, I can just remove the whole block, but I don't understand why I am getting the issue in the first place, which tells...

Block leak with __block variable

ios,objective-c,memory-leaks,objective-c-blocks,weak-references
I have a big memory leak that I have pinpointed to happen in/on requestContentEditingInputWithOptions: method. If I understand it right it happens with the img variable. If I make it __block __weak the image is nil already after I assign it (img = [UIImage...]). Am I being silly somewhere? Or...

Incompatible block pointer type? Cannot return NSArray

objective-c,nsarray,objective-c-blocks
I have a block we return an array in callback. Then I create another method to store that array as below: - (NSArray *)getUserData{ [self fetchDataByUserId:self.userID completionHandler:^(NSArray *record) { return record; }]; } I received this kind of error so please help me, I don't understand. "Incompatible block pointer types...

Translating Objective-C function call to Swift

ios,objective-c,swift,objective-c-blocks,swift-closures
This is what I have so far... func rightButtonItemsInRevealTableViewCell(revealTableViewCell: SWRevealTableViewCell!, handler:((Bool) -> (NSArray))!) { var item1: SWCellButtonItem = itemWithTitle("Delete", { (var success) in println("\(success)") } }); item1.backgroundColor = UIColor.redColor(); item1.tintColor = UIColor.whiteColor(); item1.width = 75; return item1; } I found this that is somewhat helpful but I am still getting...

How to make a boolean both static and __block? in iOS?

objective-c,objective-c-blocks,static-variables
bool _hintExist; - (void)showNotReachable { if (_hintExist) { return; } NSLog(@"Show a hint"); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ _hintExist = NO; }); } The code above is fine. There is a button to trigger the method. Actually, I don't need _hintExist be a global variable. I want to make...

blocks and the stack

cocoa,objective-c-blocks
According to bbum: 2) Blocks are created on the stack. Careful. Consider: typedef int(^Blocky)(void); Blocky b[3]; for (int i=0; i<3; i++) b[i] = ^{ return i;}; for (int i=0; i<3; i++) printf("b %d\n", b[i]()); You might reasonably expect the above to output: 0 1 2 But, instead, you get: 2...

Adding a variable to a block

ios,objective-c,objective-c-blocks
I'm using a UIAlertView + block Category found here. I'm having trouble following how he has created the blocks: typedef void (^DismissBlock)(int buttonIndex); I understand this, use it on creating my own blocks. So I created mine: typedef void (^DismissBlockWithView)(UIAlertView *alertview, int buttonIndex); I think I understand what is happening...

Is Java's Lambda equivalent to Objective-C Blocks? [closed]

objective-c,lambda,closures,objective-c-blocks
I noticied that Java's Lambda expressions seem equivalent to Objective-C blocks. Are Java's Lambda expressions exactly equivalent to Objective-C's Blocks? If not, what make's Objective-C blocks different?...

Passing the object back in a block

objective-c,objective-c-blocks
There's a number of questions and answers about how to avoid retain cycles when accessing self inside a block such as this... MYObject *obj = [[MYObject alloc] init]; __weak typeof(obj) weakObj = obj; obj.completionBlock = ^(){ NSLog(@"my message %@", weakObj.message); }; But with classes like NSTask the termination handler actually...

blocks within blocks and variable capture

objective-c,objective-c-blocks
When I have a method performing the work from a callback and the method itself references the class's properties, is that considered a leak with the way blocks are captured? @interface ClassA - (void)performClassAWorkItem1:(void (^)(NSArray *list, NSError *err)block; - (void)performClassAWorkItem2:(void (^)(NSString *string, NSError *err)block; @end @interface ClassB @property (nonatomic, strong)...

When I use Y-Combinator and block in C, I meet a strange thing in parameter value

objective-c-blocks,y-combinator
When I try to caculate sinh−1(x) using functions: double asinh_recursion(double buf, double increment, double input_var, unsigned long item_count) { if (fabs(increment) < 1E-5) { return buf; } return asinh_recursion(buf + increment, increment * (-1) * (2 * item_count - 1) * (2 * item_count -1) / (2 * item_count +...

Pass by reference for blocks

objective-c-blocks
Is there a way to pass blocks by reference? Below code prints out "Block is nil" - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { void (^block)(void) = nil; [self assignBlock:block]; if ( block ) {block();} else{NSLog(@"Block is nil");} return YES; } - (void)assignBlock:(void (^)(void))blockToAssign { blockToAssign = ^(void){ NSLog(@"Block assigned"); }; }...

Is it possible to call a block completion handler from another function in iOS?

ios,swift,block,objective-c-blocks
I have a custom UIView with a UITapGestureRecognizer attached to it. The gesture recognizer calls a method called hide() to remove the view from the superview as such: func hide(sender:UITapGestureRecognizer){ if let customView = sender.view as? UICustomView{ customView.removeFromSuperview() } } The UICustomView also has a show() method that adds it...