objective-c-blocks,y-combinator , When I use Y-Combinator and block in C, I meet a strange thing in parameter value

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


Tag: 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 + 1) / 2 / item_count * input_var, input_var, item_count + 1);
double asinh(double x) {
    if (!(fabs(x) < 1.0)) {
        printf("error asinh():wrong param x(fabs(x) > 1.0)");
        return -1.0;
    return asinh_recursion(0.0, x, x * x, 1);

it seem works. but when I try to use block and Y-Combinator to do it:

typedef void * (^YCBlock)(void *);
YCBlock Y;
double asinh_with_block(double x) {
    if (!(fabs(x) < 1.0)) {
        printf("error asinh():wrong param x(fabs(x) > 1.0)");
        return -1.0;

    Y= (YCBlock) ^ (YCBlock f) {
        return (YCBlock) ^ (YCBlock g) {
        return g(g);
        (YCBlock) ^ (YCBlock h) {
            return f(^ (void * x) { return ((YCBlock)h(h))(x); });

    typedef double (^ RECUR_BLK_TYPE)(double, double, unsigned long);
    RECUR_BLK_TYPE recur_block = Y(^(RECUR_BLK_TYPE recur_block){
        return Block_copy(^ double (double buf, double increment, unsigned long item_count){
            if (item_count < 4) {
                printf("param:%lf,%lf,%lu\n", buf, increment, item_count);

            if (fabs(increment) < 1E-5) {
                return buf;
            buf = buf + increment;
            increment = increment * (-1) * (2 * item_count - 1) * (2 * item_count -1) / (2 * item_count + 1) / 2 / item_count * (x * x);
            if (item_count < 4) {
                printf("\tbuf:%lf\n", buf);
            return recur_block(buf, increment, item_count);
    double ret = recur_block(0, x, 1);
    return ret;

but it works strangely in the output(x=0.5):


it seem like that in the block, at some time,when I pass buf=0.479167, next time when I print it, it is still 0.500000. I wanna to find why it works like this, maybe I wrote some wrong code at somewhere...


The problem is that your Y combinator is only made to work with an underlying function that takes one void * parameter and returns a void *. You can see that in the line:

return f(^ (void * x) { return ((YCBlock)h(h))(x); });

The block in there that takes x (one argument) and passed the x to another thing as one argument. For it to work with a recursive function of multiple arguments, this function must take those multiple arguments and pass them all on (of course, the types all need to be right too, because different types have different sizes, and the ABI for passing and returning things of different types is different). So you will need a different Y combinator for each function signature.

You have a recursive function that takes three parameters (two doubles and an unsigned long) and returns a double. You can (minimally) make it work by changing the relevant block in the Y combinator and coercing it from the wrong type to the right type:

return f(^ (double buf, double increment, unsigned long item_count) {
    return ((RECUR_BLK_TYPE)((YCBlock)h(h)))(buf, increment, item_count);

But to really make it clean with correct type safety without this unsafe casting would require you to carefully set up the types. Something like this:

typedef double (^Func)(double, double, unsigned long);
typedef Func (^FuncFunc)(Func);
typedef Func (^RecursiveFunc)(void *);
typedef Func (^YCBlock)(FuncFunc);

Y = ^(FuncFunc f) {
    return ^(RecursiveFunc g) {
        return g(g);
        ^(void *temp) {
            RecursiveFunc h = temp; // trick to hide the recursive typing
            return f(^(double buf, double increment, unsigned long item_count) {
                return h(h)(buf, increment, item_count);


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

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

Undefined selector with Objective-C runtime - blocks

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

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

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

blocks and the stack

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

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

Retain Cycles for Blocks Inside of 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...

Scribble uncovering bug in block use I don't understand

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

Why is this NSString null in a FireBase query block?

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

Block leak with __block variable

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

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

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

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

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

Error return a NSString inside a block

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

Pass by reference for 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"); }; }...

Background performFetchWithCompletionHandler using Blocks causes crash

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

Passing the object back in a block

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

Translating Objective-C function call to Swift

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

Confusion regarding blocks in ios

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

typedef in cocoa 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...

Method that returns block

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

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

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

iOS: UIBackgroundFetchResult completion handler inside of block

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

blocks within blocks and variable capture

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

MKDirections calculateETAWithCompletionHandler: in background state

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

Incompatible block pointer type? Cannot return NSArray

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

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

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

RACSignal combineLatest: cannot reduce

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

How to call instance methods inside a block?

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

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

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

objective-c using blocks with recursion

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

Unrecognized selector sent to instance when assigning a block property

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

Objective-C: Animations in 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; }...

How do I declare a block that returns a UIView?

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

Replacing Delegates with 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...

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

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

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

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

Block completion handler reference is nil after completing background fetch

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

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

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

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

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

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

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

Confusion over how I should use weakSelf in 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");...

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

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

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

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]; }; ....

invoking block in array with parameters

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

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

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

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

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

Retain loop in a block

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

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

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

Objective c block in a block

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

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

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