2. About
callbacks
• iOS
provides
several
ways
of
handling
call
backs
1. Selectors
• Func1on
pointer,
passing
method
as
on
argument.
2. Delegate
protocols
• Several
call
back
methods
3. Blocks
• Anonymous
func1ons
that
have
access
to
local
variables
3. Selectors
• Selectors
are
a
way
to
pass
a
method
around.
• In
Java:
reflec1on
• Common
use
in
controls
(target
–
ac1on
paMern)
[myButton addTarget:self
action:@selector(myButtonWasPressed)
forControlEvents:UIControlEventTouchUpInside];
- (void)myButtonWasPressed {
// Do something about it
}
5. Delegate
• Using
protocols
(interfaces)
you
can
define
a
contract
that
the
implementor
fulfills
• Making
call
backs:
– [locationManager setDelegate: self)
• Now
the
self
object
must
conform
to
protocol
and
it’s
protocol
methods
are
called
(call
back)
– @property id<CLLocationManagerDelegate>
delegate
6. Blocks
• Good
mechanism
for
call
back
methods
– Replaces
some
of
the
delegate
protocol
methods
• Block
is
a
chunk
of
code
that
can
be
executed
at
some
future
1me
• Blocks
are
func1ons
that
are
objects,
they
can
be
passed
as
variables.
• Code
and
Handling
task
are
related
to
each
other
• In
Java
7:
anonymous
inner
classes.
In
Java
8:
lambda
expressions
7. Java
Thread thread = new Thread(new Runnable() {
public void run() {
// The code
}
});
8. Declara1on
Form
• The
declara1on
form
of
block
is
– return_type (^block_name) (param_type,
param_type, …)
• Example
– int (^add) (int, int)
• ^ =
“I’m
a
block”
9. Block
Defini1on
• The
declara1on
form
of
block
is
– ^return_type (param_type, param_type, …)
{ ... return return_type; };
• Example
– ^int (int n1, int n2) { return n1+n2; }
10. Declara1on
and
Defini1on
together
// Declaration of block variable add
int (^add) (int, int);
// Definition for the add block variable
add = ^int (int n1, int n2)
{
return n1+n2;
};
// Usage
int number = add(2,2);
11. Block
as
an
Argument
// The method takes a block as an argument
// The block must return int and it must have
// two integer arguments
- (void) someMethod: (int (^) (int, int)) variable
{
NSLog(@"%i", variable(2,2));
}
- (void) someOtherMethod
{
// Declaration of block variable add
int (^add) (int, int);
// Definition for the add block variable
add = ^int (int n1, int n2)
{
return n1+n2;
};
// Calling the someMethod with an argument block
[self someMethod: add];
}
15. Block
Advantages
• Simplifies
code
• Keeps
code
together
• Apple
official
recommenda1on
(use
block
methods
if
possible)
16. Recap
• Selectors
– Invoke
a
method
but
you
don’t
the
name
of
the
method
at
compile
1me
• Delegates
– Great
when
there
is
need
for
several
call
back
methods
• Blocks
– Only
need
for
one
anonymous
method
with
access
of
local
variables,
blocks
are
great