Answer the question
In order to leave comments, you need to log in
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));
NSString *AppendString(NSString *string, void (^block)(NSString *stringToAppend)){
// Хочется получить доступ к stringToAppend, возможно ли это впринципи?
return [NSString stringWithFormat:@"%@<<-->>%@", string, stringToAppend];
}
NSString *newString = AppendString(@"firstString", ^(NSString *stringToAppend){
// Нужно изменить значение переменной блока и получить доступ к измененному значению внутри самого блока, те в реализации ф-ции
stringToAppend = @"secondString";
});
Answer the question
In order to leave comments, you need to log in
If I understand correctly, then something like this.
Implementation:
NSString *AppendString(NSString *string, NSString * (^block)() ){
return [NSString stringWithFormat:@"%@<<-->>%@", string, block()];
}
NSString *newString = AppendString(@"firstString", ^NSString*(){
return @"str";
});
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?";
}
}));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question