What does ^ in objective C mean? [duplicate] - objective-c

This question already has answers here:
Caret in objective C
(3 answers)
Closed 7 years ago.
What does ^ character in Objective C mean? like in the following code
TWTweetComposeViewControllerCompletionHandler
completionHandler =
^(TWTweetComposeViewControllerResult result) {
switch (result)
{
...
}
[self dismissModalViewControllerAnimated:YES];
};

It denotes a "block", a piece of code that can be packaged into an object and used later. In your example it specifies a completion handler to be called later, presumably when the user clicks "OK" or some similar button to close an alert.
Blocks can also be used with Grand Central Dispatch and in that case they are used to produce a unit of code that can be run on another thread, both synchronously and asynchronously.

This is a "block", you can read about this in the Apple-Developer-doc, it's mainly used for Multithreading.

It's used as part of the definition of a block:
^(return_type retval) {
statements;
}
You'll see it as part of declarations of blocks too.

Related

How to return outer function from inside async inner function in Objective-C

I want to return from outer function from inside async inner function.
In swift, I would have used completion handler for this purpose which would escape from function. But in Objective-C, completion handler won't actually return from function:
My function looks like this:
-(void)chosenFrom:(NSDictionary<NSString *,id> *)info{
[self asyncCode:info withCompletion:^(NSData *imageData) {
if(imageData) {
// I want to return from chosenFrom function ***inside here.***
}
}];
// This is to illustrate completion handler don't escape
[self checkCompletionEscaping:^(NSString * lad) {
NSLog(#"Check me %#", lad);// It would print all 3 lines below.
}];
}
-(void) checkCompletionEscaping:(void(^)(NSString * lad)) completion {
completion(#"Hello"); // completion handler should've escaped from func.
completion(#"Shivam");
completion(#"How are you");
}
If I were to use Swift, I could have easily returned from outer function from inside inner function using completion handler:
private func getHistoryKeys(searchterm: String, completion: #escaping () -> ()) {
let url = PubmedAPI.createEsearchURL(searchString: searchterm)
let task = session.dataTask(with: url) { (data, response, error) in
if let error = error {
completion() // This would work as return
} else {
completion() // Same as return
}
}
task.resume()
}
PS: escaping means returning from function just like return statement.
Easier is just to call another function that tells it's completed.
-(void)chosenFrom:(NSDictionary<NSString *,id> *)info{
[self asyncCode:info withCompletion:^(NSData *imageData) {
if(imageData) {
[self completedAsync:imageData];
}
}];
}
-(void)completedAsync:(NSData*) imageData {
// do your thang.
}
It seems you've asked the same question twice in different ways and people are stuck helping you. This isn't an answer as such, as I don't really know the question, but hopefully this might either help you find the answer or ask the question differently so people can help you.
Let's start with your statement:
escaping means returning from function just like return statement
and you've referred to using #escaping in Swift. While the term escaping might be used in some language to refer to what you say it is not what it means in Swift at all.
It is reasonable to be confused over what it means in Swift, as it essentially makes what could/should be a hidden compiler optimisation visible to the programmer in the language. The definition in Swift is:
A closure is said toescape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write #escaping before the parameter's type to indicate that the close is allowed to escape.
One way that a closure can escape is by being stored in a variable that is defined outside the function. As an example, many functions that start an asynchronous operation take a closure argument as a completion handler. The function returns after it starts the operation, but the closure isn't called until the operation is completed – the closure needs to escape, to be called later.
The Swift Programming Language (Swift 4.2)
What this is telling you is that #escaping affects how the closure may be stored and used, not what the closure itself actually does when called. When invoked a closure does the same operations regardless of whether it is marked as #escaping or not.
Moving on, the example used to illustrate #escaping has relevance to what appears to be your situation – you apparently wish to have a method, say A, initiate an asynchronous operation, say *B**, passing it a closure, say C, which when invoked later will cause A to return. That is impossible as when C is invade there is no invocation of A to return from. Look at the example again, emphasis added:
One way that a closure can escape is by being stored in a variable that is defined outside the function. As an example, many functions that start an asynchronous operation take a closure argument as a completion handler. The function returns after it starts the operation, but the closure isn't called until the operation is completed
After A has started B it returns, by the time C is invoked the invocation of A which started B has already returned. You are apparently asking for the impossible!
So what might be you trying to do?
Your intent might be to make A and the asynchronous operation it starts B appear as a single synchronous unit and for A not to return until B has done its work.
There are rare cases when wrapping asynchronicity as synchronous operations is required, and many more cases where people attempt to do it to make asynchronicity easier to handle but who end up destroying all the benefits of asynchronicity in the process. To do such wrapping often looks deceptively simple; but unless you have a good grasp of the GCD block model, semaphores, threads, blocking and deadlock it holds traps for the unwary.
If your intent is too try to wrap asynchronicity the better route is to embrace it instead, in your case figure out how to make your closure C do what is needed when it has been called asynchronously longer after the corresponding invocation of your method A has terminated and is no more. Thirty years ago asynchronicity was the esoteric end of day-to-day programming, today it is at its core, you need to understand and use it.
If after trying to embrace asynchronicity you decide you have one of those rare cases when it needs to hidden inside of a synchronous wrapper do a search on SO for asynchronous, semaphore etc. and you should find a solution.
If you get stuck with asynchronicity, or are actually asking about something completely different, ask a new question, show what you've done/tried/etc., and someone will undoubtedly help you take the next step.
HTH

Kotlin: Inner scope - This [duplicate]

This question already has answers here:
How to reference a lambda from inside it?
(4 answers)
Closed 7 years ago.
I just made use of Kotlins auto refactor and it basically left me with this:
coverView.viewTreeObserver.addOnPreDrawListener {
coverView.viewTreeObserver.removeOnPreDrawListener(this)
true
}
Which does not work. IntelliJ shows me that this refers to the outer class but not to the OnPreDrawListener. Why is that? The kotlin docs say that this always refer to the inner most scope.
To fix your code you can use object expression instead of lambda here:
coverView.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
coverView.viewTreeObserver.removeOnPreDrawListener(this)
return true
}
})
this expression in function expression (and the lambda you pass to the addOnPreDrawListener method is function expression) allows you to access lambda's closure, i.e. variables declared in its outermost scope, not the lambda itself.

Definition of Method, Function, Operation, Procedure, Subroutine whats the exact difference? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Are there official definitions for these terms in OOP?
Or have they just evolved over time and depending on your former computer science education (or even your age) you use one or the other?
So far i found good definitions of method vs. function:
Difference between a method and a function
A function is a piece of code that is called by name.
... All data that is passed to a function is explicitly passed.
A method is a piece of code that is called by name that is associated
with an object.
And function vs. procedure:
What is the difference between a "function" and a "procedure"?
A function returns a value and a procedure just executes commands.
A procedure is a set of command which can be executed in order.
In most programming languages, even functions can have a set of
commands. Hence the difference is only in the returning a value part.
Even if there are subtle differences in the definition by the authors the main aspect seems to be: A method is always something which operates on an object in contrast to a function which gets all data passed to it by its parameters. If a function does not return a value it is called a procedure.
But how are subroutine and especially operation linked to these terms?
EDIT: Since this seems to be too broad here is an attempt to narrow it down: method, procedure and function are pretty clear from my former research. Also subroutine is not that vague anymore.
So the question is: What is an operation in the field of computer science?
The following is my understanding. Note that these are all "soft" definitions - there is no official definition of any of these, and so the exact meaning may vary between languages. (For example, "static methods" in Java and C# don't fit my definition of "method", unless you consider classes to be objects)
A subroutine is "some code that you can call whenever". It's literally a routine that is called by other routines (hence a sub-routine). "Subroutine" and "routine" seem to be quite archaic terms.
Think of BASIC's GOSUB instruction: (never mind that BASIC is a terrible language)
10 PRINT "Hello"
20 GOSUB 100
30 PRINT "Goodbye"
40 GOSUB 100
50 END
100 PRINT "World"
110 RETURN
This prints:
Hello
World
Goodbye
World
In Visual Basic, a subroutine or Sub is a function which doesn't return anything.
A procedure is the same thing as a subroutine, but less archaic.
A procedure can also mean a function which doesn't return anything.
A function is like a procedure, but instead of just being a list of commands, it can take parameters and return a value. You should be familiar with functions from many languages, but here's an example in C++:
#include <iostream>
using namespace std;
int calculate(int a, int b) {
return a + b - 2;
}
int main() {
cout << calculate(5, 2) << endl;
cout << calculate(100, 20) << endl;
int i = calculate(5, 1);
for(int k = 0; k < i; k++) // repeat the next line i times
cout << "Hello" << endl;
}
This prints:
5
118
Hello
Hello
Hello
Hello
Notice that the function calculate doesn't do the printing itself - instead, it returns a number which main can choose to print, or to do something else with. The third call to calculate returns 2, but the 2 isn't printed - instead, it determines how many times "Hello" is printed.
A function with no arguments, that returns nothing, is equivalent to a procedure (or subroutine).
A method is a function which can be called on an object. You might be familiar with non-static methods from Java or C#. A method has access to the state of the object it was called on (which is called the receiver).
Unlike with functions, methods are often polymorphic on the type of the receiver - it's not possible to directly see which sequence of commands will run when you make a method call.
A simple example of methods in Java, demonstrating polymorphism:
class Car {
int getNumberOfWheels() {return 4;}
void printNumberOfWheels() {
System.out.println(getNumberOfWheels());
}
}
class HondaCivic extends Car {
// no code here
}
class ReliantRobin extends Car {
int getNumberOfWheels() {return 3;}
}
class Main {
public static void main(String[] args) {
Car h = new HondaCivic();
Car r = new ReliantRobin();
h.printNumberOfWheels();
r.printNumberOfWheels();
}
}
This prints:
4
3
even though you might think that printNumberOfWheels always prints 4 - subclasses can "intercept" the getNumberOfWheels method call.

ObjC Macros -- can I include check to see if a variable is defined within the current scope? [duplicate]

This question already has answers here:
Conditional macro expansion
(3 answers)
Closed 8 years ago.
This isn't the macro that I'm trying to create, but this analogy of attempting to create a custom logging function that works in Obj-C and C contexts illustrates the point:
#define Log(_s, ...) do { \
/* obviously this won't work as written, */\
/* but it's what i'm trying to accomplish: */\
#if (self && _cmd) /* \
LogObjectiveC(_s, ##__VA_ARGS__); \
#else \
LogC(_s, ##__VA_ARGS__); \
#endif \
} while (0)
In this example, we're trying to consolidate two macros that are used depending on where they are defined. (LogObjectiveC is used when inside an Obj-C method, and LogC is used when inside a C function.
Is it possible check for the existence of the 'hidden' arguments (self and _cmd) inside the Macro definition?
This isn't possible, because methods, functions and parameters don't exist at macro expansion time. Macros are expanded by the preprocessor before the compiler does anything with your code.
The closest thing I can think of would be to inspect __func__ at runtime and see whether it starts with "+[" or "-[", since all Objective-C methods start with one of those and no legal C or C++ function can.
I'm marking Chuck's as the correct answer, thanks for answering.
After another 15 minutes of googling, I stumbled on this duplicate question: Conditional macro expansion (which actually goes along the lines of #Chuck's suggestions)

difference of datatypes used before main() function [duplicate]

This question already has answers here:
Difference between void main and int main in C/C++? [duplicate]
(8 answers)
Closed 8 years ago.
What is the beneficial effects and difference between using main() function as
void main()
or
int main(void)
A main function is called by a pre-load library that runs upon execution by the operating system. Many operating systems handle the result of an executable - and declaring main to return a type of int means that the main function can return a value. Obviously declaring main to return a type of void means that the main function cannot return a value - and some compilers will not permit this depending on what the target architecture of your build is.
The difference between declaring a function () or (void) is documented many times elsewhere on StackOverflow.
if you want your application to have the ability to return a value, you must use
int main(void).
First is wrong, second is correct. End of story.