Blocks vs private methods? - ios

What are the disadvantages of using a block to define a private method within a method, instead of using a real private method? Is there any apart from not being able to call the method from somewhere else?
Example:
-(NSDictionary*)serialize
{
NSMutableDictionary* serialization = [NSMutableDictionary dictionary];
TwoArgumentsBlockType serializeItemBlock = ^void(MyItemClass* item, NSString* identifier)
{
if (item)
{
// serialization code
}
};
serializeItemBlock(self.someItem1, kSomeIdentifier1);
serializeItemBlock(self.someItem2, kSomeIdentifier2);
serializeItemBlock(self.someItem3, kSomeIdentifier3);
serializeItemBlock(self.someItem4, kSomeIdentifier4);
serializeItemBlock(self.someItem5, kSomeIdentifier5);
serializeItemBlock(self.someItem6, kSomeIdentifier6);
serializeItemBlock(self.someItem7, kSomeIdentifier7);
serializeItemBlock(self.someItem8, kSomeIdentifier8);
serializeItemBlock(self.someItem9, kSomeIdentifier9);
serializeItemBlock(self.someItem10, kSomeIdentifier10);
serializeItemBlock(self.someItem11, kSomeIdentifier11);
return serialization;
}

I think the 3 biggest drawbacks are:
The block isn't reusable, as you mention.
The block isn't testable--you can't write a unit test that verifies the block does what you think it does.
The code is less readable. When you're reading this method, what's important is that a series of things are serialized, not the details of how the serialization is implemented.
Moving this block into a method would resolve all of these issues. If the block is used by some API that takes a block callback as an argument, you can always return the block from a method.

Clarity of the code is important.
Methods allow you to encapsulate entire sections of code apart from each other, and can make it easier to read..
Another reason to choose private methods over blocks is memory management. This is far to big of a topic to discuss here, but sufficed to say that blocks are weird in the memory management, and don't act like any other code structure in that regard.

Arguably it's harder to navigate the code - you tend to have entry points buried rather obscurely in the middle of some function, and there's no function name you can see in the debugger or search for, which can make debugging and tracing a little harder.

Related

Can I implement a property setter in such a way that it calls another method generically to perform the set?

Consider the below setters:
- (void)setWinterStatus:(NSString *)status
{
NSLog(#"Variable update called");
if (_status != status)
{
[_status release];
_status = [status retain];
NSLog(#"Variable actually updated");
}
}
- (void)setCharacterState:(EnumCharacterState)state
{
NSLog(#"Variable update called");
if (_state != state)
{
_state = state;
NSLog(#"Variable actually updated");
}
}
Notice the methods are similar - it logs a generic message, checks if it's actually changing, effects the change, and logs if it does so. If I had enough such methods, I might want to write a wrapper, so that I could simply write:
- (void)setCharacterState:(EnumCharacterState)state
{
[setValue:#(state) forSelector:#selector(state)];
}
But I'm not sure if this is possible. I can't use KVO as it seems the KVO code added by default actually call's the setter, so doing so results in endless recursion. I don't know how to get the instance variable from #selector(state), nor check whether it needs release/retain. Any way to do this?
One note: the object type's base class has to remain NSObject; I can't use NSManagedObject as a base and handle my own KVO.
Edit:
So there apparently is a way using the runtime c functions (see accepted answer); seems like it could take some time to get right, but I found another solution in the interim. I register myself an an observer for all the methods I want to 'wrap', observing NSKeyValueObservingOptionNew, NSKeyValueObservingOptionOld, and NSKeyValueObservingOptionPrior. Then in the prior handler, I NSLog(#"Variable update called"), and in the update handler, I NSLog(#"Variable actually updated"). This seems to be working out well :)
Short Answer: Yes, but don't.
Long Answer:
Assuming you want to do this for educational reasons (rather than just have the compiler create the setter for you, the default in recent compilers) it is possible, but it is non-trivial.
You've noticed one difference - whether you need to retain/release (assuming MRC) - but there are more. For example, consider the simple line:
_state = state;
What does it do? Copy a byte? Two bytes? Eight bytes? The code might look the same in different setters but it compiles to different machine code.
And then there are copy and weak attributes on properties to consider...
Still considering doing this?
You'll need to be comfortable with what void ** means, copying data of variable length via pointers, etc. Then take a look at object_setInstanceVariable, property_getAttributes etc. - these are all C functions, you'll find them in Objective-C Runtime Reference.
From that you'll find you need to know about type encodings (which will help you with how many bytes to copy around), and more...
Have fun!
HTH

Closures in Swift, blocks in Objective-C: their usefulness and when to use

I've found an Objective-C SocketIO library and am trying to implement it in my first Swift app. Here's the code I'm trying to port:
__weak typeof(self) weakSelf = self;
self.socket.onConnect = ^()
{
weakSelf.socketIsConnected = YES;
[weakSelf mapView: weakSelf.mapView didUpdateUserLocation: weakSelf.mapView.userLocation];
};
From my limited understanding ^() {} is a block in Objective C. I've looked into it and closures seem to be a loose equivalent Swift. My first obvious question is how do I get the same result in Swift?
I've tried the following but get the error fatal error: unexpectedly found nil while unwrapping an Optional value (lldb):
self.socket.onConnect = { () -> Void in
println("Connected!")
}
Also, behind the scenes what's happening here? An asynchronous callback function would seem appropriate but wasn't used and I'd like to understand why.
UPDATE
As pointed out by #jtbandes, socket was in fact Nil as this code was running outside of the connection callback (I know, a very silly mistake). Solution to first question:
SIOSocket.socketWithHost(server) { (socket: SIOSocket!) in
self.socket = socket
self.socket.onConnect = { () -> Void in
println("Connected!")
}
}
Objective-C blocks and Swift closures are more than loose equivalents. They are direct equivalents.
A block/closure is an anonymous function that inherits it's enclosing scope.
I'm still working in Objective-C, so I'm used to its terminology. I'll use those terms
Blocks are useful in lots of ways.
Completion code is one example.
Without blocks, if you're setting up an async networking class, you might give it a delegate property, and define a protocol with callbacks that the class uses to notify it's delegate about events like download complete, errors, etc.
This makes for a lot of message handling infrastructure in lots of different places. You have to define a protocol. You have to add a delegate property to the networking class. You have to implement a set of delegate messages in the client class. You may have to pass context information to the callbacks, etc.
With blocks, you invoke a method that asks for a networking service, and provide a completion block. When the service is complete, it invokes the provided code block. You might add parameters to the completion block like a pointer to the data, a success boolean, or whatever is appropriate. The code block can have access to all the variables defined in its enclosing scope, which can be very helpful.
You can also save blocks into collections, you can use blocks in sort methods, and int lots of other cases.
The code you posted simply sets a block property on the object in question, self.socket. It looks like it is a block of code that gets called after a socket connection is established.
There are direct equivalents to this in Swift. I've only poked around in Swift however, so I'll leave it to others to help you with the translation.
I suggest browsing through Apple's classes for ideas on how to use blocks. Take a look at NSURLConnection and NSURLSession if you're interested in async networking. Take a look at the block-based view animation methods that take an animation block and a completion block. Those will give you an idea of the ways you can use blocks for handling async events, or passing code to a class to get work done.
Another interesting use of blocks is in handling collections like arrays. There are methods that take an NSComparator block and sort an array, and there are methods that will enumerate through an array, performing a block of code on each element and/or selecting a subset of the elements and returning an index set of the array indexes.
Duncan

Why do we needed category when we can use a subclass? and Why we needed blocks when we can use functions?

These two questions are quite common when we search it but yet I need to get a satisfying answer about both.When ever we search a difference between say subclass and a category we actually get definition of both not the difference.I went to an interview to a very good MNC working on iOS and I was encountered with these two questions and I gave almost all the answers I have read here but the interviewer was not satisfied.He stuck to his questions and was that-
Why do we needed category when we can use a subclass?
Why we needed blocks when we can use functions?
So please explain me what specific qualities blocks and category add in objective C that their counter part can't do.
First...
Just reading the documentation "Subclassing Notes" for NSString shows why creating categories is sometimes better than subclassing.
If you wanted to add a function -(void)reverseString (for instance) to NSString then subclassing it is going to be a massive pain in comparison to categories.
Second...
Blocks are useful for capturing scope and context. They can also be passed around. So you can pass a block into an asynchronous call which then may be passed elsewhere. TBH you don't care where the block is passed or where it is finally called from. The scope captured at the time of creating the block is captured too.
Yes, you can use methods too. But they both have different uses.
Your questions are a bit odd. It's like asking...
Why do hammers exist when we can just use wrenches?
You can't use subclassing when someone else is creating the objects. For instance, NSString is returned from hundreds of system APIs, and you can't change them to return MyImprovedString.
Functions split up the logic; blocks allow you to write it closer together. Like:
[thing doSomethingAndWhenFinishedDo: ^{ some_other_thing; }];
the same code written with functions would put the second part of the logic several lines away in the file. If you have a few nested scopes in your logic then blocks can really clean it up.
Why do we needed category when we can use a subclass?
Categories let you expand the API of existing classes without changing their type. Subclassing does the same thing but introduces a new type. Additionally subclassing lets you add state.
Why we needed blocks when we can use functions?
Block objects are a C-level syntactic and runtime feature. They are similar to standard C functions, but in addition to executable code they may also contain variable bindings to automatic (stack) or managed (heap) memory. A block can therefore maintain a set of state (data) that it can use to impact behavior when executed.
You can use blocks to compose function expressions that can be passed to API, optionally stored, and used by multiple threads. Blocks are particularly useful as a callback because the block carries both the code to be executed on callback and the data needed during that execution
Category : It is used if we want to add any method on a given class whose source is not known. This is basically used when we want to alter the behaviour of any Class.
For example : If we want to add a method on NSString to reverse a string we can go for categories.
Subclassing : If we want to modify state as well as behaviour of any class or override any methods to alter the behaviour of the parent class then we go for subclassing.
For example : We subclass UIView to alter its state and behaviour in our iOS code.
Reference :
When to use categories and when to use subclassing?
What is the difference between inheritance and Categories in Objective-C
We need new method but we don't need new class so we need category.
We need function but we don't need named function so we need block.

What is the use of storing the block in an instance variable

I am aware that blocks are one of the latest feature added in ios. But I am really finding a
tough time learning it .
I have seen people doing the following
typedef void(^CallBackBlk) (NSString *);
#property(copy,nonatomic)CallBackBlk block;
and in .m class
-(void)doSomething:(CallBackBlk )cb{
self.block=cb;
}
I never understood what is the use of assigning it to cb here. Can't I simply do the following
-(void)doSomthing{
block(#"my string");
}
I am really not getting the purpose of storing the block in instance variable. Can any help
me with an example. Any help is greatly appreciated
In your doSomething method, where does block come from?
Answer that, and you'll have your reason.
Ah -- the commentary makes the question clear. Snark served a purpose (snark and too lazy to type out a real answer on my iPhone at 7AM :).
An instance variable is just a slot to put things. Nothing is in that slot to start with.
In your case, you could implement:
-(void)doSomething:(CallBackBlk )cb{
cb();
}
However, typically, a callback is used when you do something asynchronously. For example, you might do:
[myObject doSomething:^{
NSLog(#"did something");
}];
And then:
-(void)doSomething:(CallBackBlk)cb {
dispatch_async(... global concurrent queue ..., ^{
... do some work ...
cb();
});
}
That is, doSomething: will return as soon as the dispatch_async() happens. The callback block is used to callback to let you know that asynchronous operation is done.
Of course, still no need for an instance variable. Take that class that does something a bit further; make it some kind of relatively complex, state transitioning, engine. Say, like your average internet downloader or compute heavy simulation engine. At that point, lumping all your background work into a single method would be overly complex and, thus, shoving the callback block(s) (there may likely be more than one; a progress updater, a completion block and/or an error block, for example) into instance variables allow the class's implementation to be subdivided along lines of functionality more cleanly.
What is the use of storing the block in an instance variable
Perhaps to be able to access it later?
You would do that if you want to invoke the block later, after the method that assigns it has already returned.
Consider for example an object that manages a download. You might want to have a block that gets invoked when the download completes (e.g. to update the UI), but you don't want the download method to have to wait until that happens (because it might take a long time).
maybe and example of use will help..
one use for storing it as a variable i have found is if you have multiple views that all access another view (for me it was a map on the next view) i used blocks that were setup by the previous view (set the default location for the map, initialise markers and so forth) then passed it through to the next view, where it would run it, setting up the map. it was handy having the block use the local variables of the previous view to access certain attributes. it wasnt the only way to do it, but i found it was a nice clean way of going about it.
and here is an example of what gets run in the viewDidLoad of the mapview
if(setupMap){
setupMap(mapView);
}
if(gpsUpdate){
gpsUpdate(mapView);
}
if(addMarker){
addMarker(mapView);
}
now if those blocks were assigned (the if statement check if they are nil), it would run them and do the appropriate setup for the map. not every view needed to do those, so they would only pass to the map view what needed to be done. this keeps the map view very general purpose, and code gets reused a lot. write once use lots!
To use the block, you call your doSomething: method:
CallBackBlk laterBlock = ^(NSString *someString) {
NSLog(#"This code is called by SomeClass at some future time with the string %#", someString);
};
SomeClass *instance = [[SomeClass alloc] init];
[instance doSomething:laterBlock];
As you code the implementation of your class, it will presumably reach some condition or finish an action, and then call the laterBlock:
if (someCondition == YES) {
self.block("Condition is true");
}

What are the Dangers of Method Swizzling in Objective-C?

I have heard people state that method swizzling is a dangerous practice. Even the name swizzling suggests that it is a bit of a cheat.
Method Swizzling is modifying the mapping so that calling selector A will actually invoke implementation B. One use of this is to extend behavior of closed source classes.
Can we formalise the risks so that anyone who is deciding whether to use swizzling can make an informed decision whether it is worth it for what they are trying to do.
E.g.
Naming Collisions: If the class later extends its functionality to include the method name that you have added, it will cause a huge manner of problems. Reduce the risk by sensibly naming swizzled methods.
I think this is a really great question, and it's a shame that rather than tackling the real question, most answers have skirted the issue and simply said not to use swizzling.
Using method sizzling is like using sharp knives in the kitchen. Some people are scared of sharp knives because they think they'll cut themselves badly, but the truth is that sharp knives are safer.
Method swizzling can be used to write better, more efficient, more maintainable code. It can also be abused and lead to horrible bugs.
Background
As with all design patterns, if we are fully aware of the consequences of the pattern, we are able to make more informed decisions about whether or not to use it. Singletons are a good example of something that's pretty controversial, and for good reason — they're really hard to implement properly. Many people still choose to use singletons, though. The same can be said about swizzling. You should form your own opinion once you fully understand both the good and the bad.
Discussion
Here are some of the pitfalls of method swizzling:
Method swizzling is not atomic
Changes behavior of un-owned code
Possible naming conflicts
Swizzling changes the method's arguments
The order of swizzles matters
Difficult to understand (looks recursive)
Difficult to debug
These points are all valid, and in addressing them we can improve both our understanding of method swizzling as well as the methodology used to achieve the result. I'll take each one at a time.
Method swizzling is not atomic
I have yet to see an implementation of method swizzling that is safe to use concurrently1. This is actually not a problem in 95% of cases that you'd want to use method swizzling. Usually, you simply want to replace the implementation of a method, and you want that implementation to be used for the entire lifetime of your program. This means that you should do your method swizzling in +(void)load. The load class method is executed serially at the start of your application. You won't have any issues with concurrency if you do your swizzling here. If you were to swizzle in +(void)initialize, however, you could end up with a race condition in your swizzling implementation and the runtime could end up in a weird state.
Changes behavior of un-owned code
This is an issue with swizzling, but it's kind of the whole point. The goal is to be able to change that code. The reason that people point this out as being a big deal is because you're not just changing things for the one instance of NSButton that you want to change things for, but instead for all NSButton instances in your application. For this reason, you should be cautious when you swizzle, but you don't need to avoid it altogether.
Think of it this way... if you override a method in a class and you don't call the super class method, you may cause problems to arise. In most cases, the super class is expecting that method to be called (unless documented otherwise). If you apply this same thought to swizzling, you've covered most issues. Always call the original implementation. If you don't, you're probably changing too much to be safe.
Possible naming conflicts
Naming conflicts are an issue all throughout Cocoa. We frequently prefix class names and method names in categories. Unfortunately, naming conflicts are a plague in our language. In the case of swizzling, though, they don't have to be. We just need to change the way that we think about method swizzling slightly. Most swizzling is done like this:
#interface NSView : NSObject
- (void)setFrame:(NSRect)frame;
#end
#implementation NSView (MyViewAdditions)
- (void)my_setFrame:(NSRect)frame {
// do custom work
[self my_setFrame:frame];
}
+ (void)load {
[self swizzle:#selector(setFrame:) with:#selector(my_setFrame:)];
}
#end
This works just fine, but what would happen if my_setFrame: was defined somewhere else? This problem isn't unique to swizzling, but we can work around it anyway. The workaround has an added benefit of addressing other pitfalls as well. Here's what we do instead:
#implementation NSView (MyViewAdditions)
static void MySetFrame(id self, SEL _cmd, NSRect frame);
static void (*SetFrameIMP)(id self, SEL _cmd, NSRect frame);
static void MySetFrame(id self, SEL _cmd, NSRect frame) {
// do custom work
SetFrameIMP(self, _cmd, frame);
}
+ (void)load {
[self swizzle:#selector(setFrame:) with:(IMP)MySetFrame store:(IMP *)&SetFrameIMP];
}
#end
While this looks a little less like Objective-C (since it's using function pointers), it avoids any naming conflicts. In principle, it's doing the exact same thing as standard swizzling. This may be a bit of a change for people who have been using swizzling as it has been defined for a while, but in the end, I think that it's better. The swizzling method is defined thusly:
typedef IMP *IMPPointer;
BOOL class_swizzleMethodAndStore(Class class, SEL original, IMP replacement, IMPPointer store) {
IMP imp = NULL;
Method method = class_getInstanceMethod(class, original);
if (method) {
const char *type = method_getTypeEncoding(method);
imp = class_replaceMethod(class, original, replacement, type);
if (!imp) {
imp = method_getImplementation(method);
}
}
if (imp && store) { *store = imp; }
return (imp != NULL);
}
#implementation NSObject (FRRuntimeAdditions)
+ (BOOL)swizzle:(SEL)original with:(IMP)replacement store:(IMPPointer)store {
return class_swizzleMethodAndStore(self, original, replacement, store);
}
#end
Swizzling by renaming methods changes the method's arguments
This is the big one in my mind. This is the reason that standard method swizzling should not be done. You are changing the arguments passed to the original method's implementation. This is where it happens:
[self my_setFrame:frame];
What this line does is:
objc_msgSend(self, #selector(my_setFrame:), frame);
Which will use the runtime to look up the implementation of my_setFrame:. Once the implementation is found, it invokes the implementation with the same arguments that were given. The implementation it finds is the original implementation of setFrame:, so it goes ahead and calls that, but the _cmd argument isn't setFrame: like it should be. It's now my_setFrame:. The original implementation is being called with an argument it never expected it would receive. This is no good.
There's a simple solution — use the alternative swizzling technique defined above. The arguments will remain unchanged!
The order of swizzles matters
The order in which methods get swizzled matters. Assuming setFrame: is only defined on NSView, imagine this order of things:
[NSButton swizzle:#selector(setFrame:) with:#selector(my_buttonSetFrame:)];
[NSControl swizzle:#selector(setFrame:) with:#selector(my_controlSetFrame:)];
[NSView swizzle:#selector(setFrame:) with:#selector(my_viewSetFrame:)];
What happens when the method on NSButton is swizzled? Well most swizzling will ensure that it's not replacing the implementation of setFrame: for all views, so it will pull up the instance method. This will use the existing implementation to re-define setFrame: in the NSButton class so that exchanging implementations doesn't affect all views. The existing implementation is the one defined on NSView. The same thing will happen when swizzling on NSControl (again using the NSView implementation).
When you call setFrame: on a button, it will therefore call your swizzled method, and then jump straight to the setFrame: method originally defined on NSView. The NSControl and NSView swizzled implementations will not be called.
But what if the order were:
[NSView swizzle:#selector(setFrame:) with:#selector(my_viewSetFrame:)];
[NSControl swizzle:#selector(setFrame:) with:#selector(my_controlSetFrame:)];
[NSButton swizzle:#selector(setFrame:) with:#selector(my_buttonSetFrame:)];
Since the view swizzling takes place first, the control swizzling will be able to pull up the right method. Likewise, since the control swizzling was before the button swizzling, the button will pull up the control's swizzled implementation of setFrame:. This is a bit confusing, but this is the correct order. How can we ensure this order of things?
Again, just use load to swizzle things. If you swizzle in load and you only make changes to the class being loaded, you'll be safe. The load method guarantees that the super class load method will be called before any subclasses. We'll get the exact right order!
Difficult to understand (looks recursive)
Looking at a traditionally defined swizzled method, I think it's really hard to tell what's going on. But looking at the alternative way we've done swizzling above, it's pretty easy to understand. This one's already been solved!
Difficult to debug
One of the confusions during debugging is seeing a strange backtrace where the swizzled names are mixed up and everything gets jumbled in your head. Again, the alternative implementation addresses this. You'll see clearly named functions in backtraces. Still, swizzling can be difficult to debug because it's hard to remember what impact the swizzling is having. Document your code well (even if you think you're the only one who will ever see it). Follow good practices, and you'll be alright. It's not harder to debug than multi-threaded code.
Conclusion
Method swizzling is safe if used properly. A simple safety measure you can take is to only swizzle in load. Like many things in programming, it can be dangerous, but understanding the consequences will allow you use it properly.
1 Using the above defined swizzling method, you could make things thread safe if you were to use trampolines. You would need two trampolines. At the start of the method, you would have to assign the function pointer, store, to a function that spun until the address to which store pointed to changed. This would avoid any race condition in which the swizzled method was called before you were able to set the store function pointer. You would then need to use a trampoline in the case where the implementation isn't already defined in the class and have the trampoline lookup and call the super class method properly. Defining the method so it dynamically looks up the super implementation will ensure that the order of swizzling calls does not matter.
First I will define exactly what I mean by method swizzling:
Re-routing all calls that were originally sent to a method (called A) to a new method (called B).
We own Method B
We dont own method A
Method B does some work then calls method A.
Method swizzling is more general than this, but this is the case I am interested in.
Dangers:
Changes in the original class. We dont own the class that we are swizzling. If the class changes our swizzle may stop working.
Hard to maintain. Not only have you got to write and maintain the swizzled method. you have to write and maintain the code that preforms the swizzle
Hard to debug. It is hard to follow the flow of a swizzle, some people may not even realise the swizzle has been preformed. If there are bugs introduced from the swizzle (perhaps dues to changes in the original class) they will be hard to resolve.
In summary, you should keep swizzling to a minimum and consider how changes in the original class might effect your swizzle. Also you should clearly comment and document what you are doing (or just avoid it entirely).
It's not the swizzling itself that's really dangerous. The problem is, as you say, that it's often used to modify the behavior of framework classes. It's assuming that you know something about how those private classes work that's "dangerous." Even if your modifications work today, there's always a chance that Apple will change the class in the future and cause your modification to break. Also, if many different apps do it, it makes it that much harder for Apple to change the framework without breaking a lot of existing software.
Used carefully and wisely, it can lead to elegant code, but usually, it just leads to confusing code.
I say that it should be banned, unless you happen to know that it presents a very elegant opportunity for a particular design task, but you need to clearly know why it applies well to the situation, and why alternatives do not work elegantly for the situation.
Eg, one good application of method swizzling is isa swizzling, which is how ObjC implements Key Value Observing.
A bad example might be relying on method swizzling as a means of extending your classes, which leads to extremely high coupling.
Although I have used this technique, I would like to point out that:
It obfuscates your code because it can cause un-documented, though desired, side effects. When one reads the code he/she may be unaware of the side effect behavior that is required unless he/she remembers to search the code base to see if it has been swizzled. I'm not sure how to alleviate this problem because it is not always possible to document every place where the code is dependent upon the side effect swizzled behavior.
It can make your code less reusable because someone who finds a segment of code which depends upon the swizzled behavior that they would like to use elsewhere cannot simply cut and paste it into some other code base without also finding and copying the swizzled method.
I feel that the biggest danger is in creating many unwanted side effects, completely by accident. These side effects may present themselves as 'bugs' which in turn lead you down the wrong path to find the solution. In my experience, the danger is illegible, confusing, and frustrating code. Kind of like when someone overuses function pointers in C++.
You may end up with odd looking code like
- (void)addSubview:(UIView *)view atIndex:(NSInteger)index {
//this looks like an infinite loop but we're swizzling so default will get called
[self addSubview:view atIndex:index];
from actual production code related to some UI magic.
Method swizzling can be very helpful is in unit testing.
It allows you to write a mock object and have that mock object used instead of the real object. Your code to remain clean and your unit test has predictable behavior. Let's say you want to test some code that uses CLLocationManager. Your unit test could swizzle startUpdatingLocation so that it would feed a predetermined set of locations to your delegate and your code would not have to change.

Resources