M
M
MarinaB2014-05-29 22:32:10
Objective-C
MarinaB, 2014-05-29 22:32:10

Non-standard use of blocks in Objective-C

Good day!
The question arose whether it is possible to implement the following behavior of a function with a block as a parameter: Function
declaration:

NSString *AppendString(NSString *string, void (^block)(NSString *stringToAppend));

Implementation:
NSString *AppendString(NSString *string, void (^block)(NSString *stringToAppend)){
   // Хочется получить доступ к stringToAppend, возможно ли это впринципи?
    return [NSString stringWithFormat:@"%@<<-->>%@", string, stringToAppend];
}

Usage:
NSString *newString = AppendString(@"firstString", ^(NSString *stringToAppend){
    // Нужно изменить значение переменной блока и получить доступ к измененному значению внутри самого блока, те в реализации ф-ции
    stringToAppend = @"secondString";
});

We pass one line to the function in the normal way, and change the second inside the block, and inside the function itself we add the lines and return the result. Is it possible?
PS: I know that this is a perversion, I am aware that it is possible not to implement it, I know how to use the blocks for their intended purpose. Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Ne0nX, 2014-05-29
@Ne0nX

If I understand correctly, then something like this.
Implementation:

NSString *AppendString(NSString *string, NSString * (^block)() ){
    return [NSString stringWithFormat:@"%@<<-->>%@", string, block()];
}

Usage:
NSString *newString = AppendString(@"firstString", ^NSString*(){
    return @"str";
});

G
gooddy, 2014-06-01
@gooddy

yes, a strange approach, of course, it’s more suitable with returning a value from a block, but oh well, everyone is weird as they want

typedef void(^StringPtrBlock)(NSString **str);
NSString *AppendString(NSString *string, StringPtrBlock block);

NSString *AppendString(NSString *string, StringPtrBlock block){
  // Хочется получить доступ к stringToAppend, возможно ли это впринципи?
  NSString *str;
  block(&str);
    return [NSString stringWithFormat:@"%@<<-->>%@", string, str];
}

NSLog(@"%@", AppendString(@"Lol", ^(NSString **stringToAppend) {
    if (stringToAppend) {
      *stringToAppend = @"WUT?";
    }
  }));

Output: Lol<<-->>WUT?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question