EXC_BAD_ACCESS (code=1 address=0x0) at runtime

Ok, you might be laughing at the end of this post, but I thought it is better if I put this into a searchable form, and you might in the same situation as me.

In a nutshell: I modified the signature one of my class’s initializer, this class was actually a subclass of the UIView, and after the modification every time I tried to access those class Xcode stopped with the error: EXC_BAD_ACCESS (code=1 address=0x0). It was so frustrating, that Xcode dropped me neither a build-time error nor any particular error in the error log. I spent almost a day digging into topics in StackOverflow without any solution. I have also checked the debugger, actually the view wasn’t null.

I don’t want to tease you more, so [drum rolling…]:

Actually, and accidentally I deleted the reference message call from the initializer to the superview, so this line was missing from my UIView implementation’s initWithFrame: initializer:
self = [super initWithFrame:frame];.

My bad. Hopefully next time I (and hopefully you as well;)) will find this post quicker than the other posts in the StackOverflow;).

iOS Communication Patterns Explained Part 5: Blocks

Finally, we are here;). The road was quite long from the initial solution, where we just put all of our code into one class, and we were happy that it worked to the current situation, where our code based on the delegation pattern. In this blog post we go further, and we will apply the block based solution for our small downloader class.

In the last post we applied the delegation pattern to our small app. For the 1-to-1 communication situations, like we have in our example code, using the blocks is a really good decision.

About blocks

Hopefully you have already heard about the blocks, it is a quite powerful tool and technique in Objective-C, and you can see an extensive usage of the blocks in Apple’s own frameworks. The main concept of the blocks is that you can define a block of code as standalone entity. This block of code could have parameters, could return a result, based on the logic of the block. It is quite similar to the functions, but blocks don’t need to have any name defined. Moreover block can be assigned to a variable. It means that our code can be passed to a function or a method, even in another class, and can be executed from the other entity. It is good to mention that the receiver class, which has received the block as a method parameter doesn’t even know about the sender class. Which means that those classes really loosely coupled. Isn’t it powerful? Yes, it is. With some caveats.

Retain cycles and variable scopes

Here is the first one: the retain cycle. I hope you have already heard the expression, mostly about the strong/weak property parameters. In a nutshell: if you create strong references mutually between two objects, you will end up with a retain cycle, since during the deallocation of any of the objects the ARC won’t enable to free the memory of the object while there is still a strong reference pointing to the object. The result is a memory leak.
Why is it important in case of blocks? Blocks should be considered as a separate entity, a kind of new context. If you pass a block, containing reference to self to another object, that reference for the original object will be strong. Voila, you have just created a retain cycle.
There is another interesting behavior of the blocks: by default the variables defined outside the scope of block, but visible by the block are read only. That means that the block can not modify them. In order to change this behavior, we need to define the variables with the __block keyword.

My solution in UML

After this warm-up, let see the UML diagram of the proposed solution:

Haven’t we seen it before? Yes, you are right, this is the same UML where we started, except the completionHandler parameter in the method of PMODownloader. This is the beautiful about the blocks, you can go back to the simple solution, and sacrifice a little bit complexity on the block.

What can go wrong?

There are a few (actually a lot :P) things can go wrong, let see at least 2 things.

Retain cycle and weakSelf

First of all the retain cycle I have just mentioned above. Usually it happens when you pass a reference type (an object) to another object. In this case we want to update one of the property of the self. If I would just use self in the block, I have just created a nice retain cycle. To avoid from that we should use the weak version of the self, before using and declaring the block. Something like this:
__weak __typeof__(self) weakSelf = self;
After this declaration we can use weakSelf safely in the block.

Background thread

This topic is less obvious with our current project, but could cause some facepalms. Here is the thing: The NSURLSession usually uses a background thread in order to download your data. When it is done, it will call you the recently created block… Still on the background thread. Which could be great, but if you want to update your User Interface with the changes you have to use the application main thread. For that reason I would suggest to add an NSOperation to the main queue, and execute the block code on the main queue.

Code changes

The code is getting cleaner and shorter. Let’s go through all of the files, which has been changed.

First of all we can delete the PMODataHolder.h and PMODownloaderFromURL.h files, which were our protocol definition files.

Let see what we need to change in our other files:
We definitely need to change our PMOPictureController.h:

As you can see I removed the import statement for the PMODataHolder.h and also removed the protocol from the end of the interface line.


At the //1 there is a forward declaration for our block. As you can see you can easily declare your block as a type, so later on in your code you can easily create a kind of an instances from that type. Honestly, Apple gave us a lot of ways how we can define a block, and sometimes it is really confusing. My favourite web side to help me is http://goshdarnblocksyntax.com. Feel free to use it. As you can see the delegate property reference and codes were removed as well. First of all there is the weakSelf definition, and after that the actual block is defined pretty much same as any other variable (DownloadCallBack downloadCallBack =), since the type is already declared at //1.

The first thing is here what I did is to with to the main thread with [NSOperationQueue mainQueue] addOperationWithBlock:. The NSURLSession in the PMODownloader will use a background thread and queue in order to download the picture. For the safety I switched to the main thread with the KVO update and update of the image by adding those operations as a block to the execution queue of the main thread.

And of course we need to pass the block to our downloader. I named it a completionHandler.


I removed the reference and the import statement for the PMODownloaderFromURL protocol from the header, and the only public API method has been updated with a possibility to receive a block as a parameter at //1.

At //2 there is the block magic. Actually it is just one line of code, which is calling back the block on the original object, with the downloaded raw data as a parameter. I hope I don’t need to explain more, why is this solution is more powerful and using less dependencies? Actually I can use PMODownloader for any task, where I want to download something, and I need to only pay attention to the block signature. If the downloaded file is not an image, but an XML or JSON, I can start to serialise and parse them in the block, but from the PMODownloader it is invisible, and it won’t need any further change.

What about the Unit Tests?

Since I changed before the test for PMOPictureController to a KVO event, which Key-Value change is done on the PMOPictureController, and our block based solution still triggering that observable event, we don’t really need to change anything in our test case.


My series finished with that post. I hope you have discovered at least one useful piece of information during those chapters. As you can see from the final code, usually you end up using more than one communication pattern. Even this small example I use blocks for the 1:1 communication, KVO for broader audition, to inform other classes that the image is available, and the Notification Center in the case of there is an error during the download.

You can download the project from here, and by switching branches you can switch between the different solutions: https://github.com/petermolnar-hu/CommunicationReFactory

Feel free to comment!

Tune your header file Part 2: Nullability

In the first post I put the focus on the initializers, in this post I would like to put the nullability into the spotlight. I would also explain why is it a good practice, and how it will help you migrate your existing Objective-C code into Swift.


The idea behind using the nullable/nonnull keyword is to protect our code against the accidental nil values, which might crash our app in runtime. As I mentioned in the Embrace compile time errors post, it is better that the developer has early warning about the problem, and it won’t escalate to the runtime error.

With the Nullable and Nonnull keywords we, as developers can clearly and explicitly define that the class property or the method variables and return value can be nil or not. Examples:

@property (weak, nonatomic, nullable) id progressDelegate;
For an object type property it is quite easy to use, just add the nullable/nonnull for the property attributes.

@property (unsafe_unretained, nonatomic) BOOL isAllModelParsed;
For the primitive types there is no sense to add nullability.

- (nullable instancetype)init;
As you can see even the initializer return value (instancetype) can have the nullability attribute.

- (nullable instancetype)initWithModelControllers:(nullable NSArray *) models NS_DESIGNATED_INITIALIZER;
It works together with generics and applicable for the method parameters, not just the return values.

- (void)startPopulateDrawNumbersWithCompletionHandler:(void (^_Nonnull)(BOOL wasSuccessfull, NSArray * _Nullable numbers))callback;
And can be applied on the blocks as well. Please note the use of underscore (_Nonnull/_Nullable). Essentially this is same, the only difference is that without underscore you can use before the type definition, but after the type definition (like NSArray) you can use only the underscored version. Unfortunately blocks a are a quite picky about this. You can find a good set of different definition here: http://stackoverflow.com/a/33682230/3074959

What to consider and decide

Although you can either just ignore this advise, or try to cheat a little bit with NS_ASSUME_NONNULL_BEGIN and NS_ASSUME_NONNULL_END macros, if you want to implement the nullability in your header file, then be prepared to challenge all of your not primitive type properties and the methods parameters with the return type as well.

If you set up even one variable with the nullability, clang will warn you to with the “Pointer is missing nullability type specifier” message. Which means that ALL of your pointer in the header file need to have a clearly defined nullability.


When the nullability properly set up and defined for all of our classes, it helps us in the early detection of the error or malfunction in cases when nil passed or set up for the variable.

If you think about migrate your existing code to Swift, which needs to be done soon or later, you have already one step closer to figure out, which variable need to be an optional and which not.

Tune your header file Part 1: Designated and Convenience initializers

Let’s talk about the header (.h) files. Probably you know that what is defined in the header file has a public visibility. Any method or property declared here can be accessible all of the other classes, which are importing this file. That is one of the reason why we need to plan carefully what is going to be in this file, which is sometimes referred as the public API of the class. There are 2 important things I wanted to discuss in this series, one is the designated initializer, the other is the nullable/notnull keywords. Usually you will use both of them in the Objective-C header files.

Designated initializer

You probably have heard about them, but let me recap: Before we can use any object, first we need to allocate a memory address to it, and after the allocation we need to initialize it. Usually it is done by [[MyClass alloc] init] form. Obviously you are able to overwrite the default init method in the implementation file (MyClass.m), but there are other reasons not to do so.
One of the reasons is that your object probably need to have some other objects or variables handed over and set up when the object created, with its initial state. For example let say MyObject have two properties: (BOOL)isNightMode and (MyOtherObject *)theObjectDoingSomethingElse. If you want to instantiate an object from code and set up those properties, you probably will do in this way:

The problem with that solution is whether you, or any of your developer colleague can easily forget to set the isNightMode and theObjectDoingSomethingElse right after initializing the object. So the best practice is to pass those variables at the same time, when we instantiate the class, like this:

As you can see we are passing the values at the time of init, which means that we need to create a public method with the same signature (same count and type of parameters), and if we forget to do so we will have a build error when you compile your project. We will have a build error as well, if we want to use the defined method without all of the required parameters. As a best practice we also want this method to be the default initializer, which Apple calls Designated initializer. There is a macro defined for that purpose, which is the NS_DESIGNATED_INITIALIZER. Don’t forget: You can have only one designated initializer, usually the one which calls [super init].

If we want to be fully covered we also need to take care of the default init method, since we don’t want anybody to use this anymore . There is a very nice trick with using the macro NS_UNAVAILABLE. Just simply put the following code into your header file and the default init won’t be available anymore.
- (nullable instancetype)init NS_UNAVAILABLE;
Let’s put everything together in code then: My header file (MyObject.h) will look like this:

My implementation file will look like this:

//1 As you might noticed, I moved the properties from the header file to the implementation file (opening a new section, with @interface). In this way they won’t be part of the public API anymore, so they will be set at the init time, and can not be changed. In the other hand we lose the opportunity to change those properties from outside of the class. If you want to still change any of them, the easiest way is to move it back to the header file. Nevertheless, don’t forget the encapsulation principle: always try to challenge your decision when you want to expose a property to the publicity.
//2 Here is our new designated initializer. As you can see the parameters passed in the method parameter list have been assigned to the private variables (starting with underscore).

Convenience initializers

I think we did a good work here so far, but what if we need an initializer which won’t require the nightMode for our convenience? No worries, we can handle this, add the initWithTheOtherObjectDoingSomethingElse:alreadyExisitingObject method to the MyObject.h:

We also need to add the implementation to the MyObject.m:

That’s it. The only drawback to this solution is that we made the isNightmode as a constant NO, but if we are doing it intentionally, then it’s OK. Usually this approach is used when we need a convenient way to initialize the object, keeping some of the parameters hard-coded. This is why it is called convenient initializer. I would suggest to have the designated initializer including all of the injected variables, and create convenience initializers which serve your needs.

The technique above is similar to dependency injection, but in order to have a proper dependency injection we need to involve protocols.

Let me know your thoughts!

iOS Communication Patterns Explained Part 4: Delegation

In the last post we changed the communication between our classes to be based on the Key-Value Observation. As we could see KVO is not the best solution for our problem, but sometimes can be helpful, if we need to observe one particular object property changes.

In this post I will modify the communication to have the same characteristic as the delegation software design pattern. Let see what changes are required in the class diagram in order to achieve our target:

In the UML diagram above you see two «protocol», which is pretty much same as the «interface» in other Object Oriented Programming languages (if they support this particular principle). The protocol or the interface sometimes called as a contract, and all of the classes implement the protocol or interface will have as a “contractual obligation” to implement all of the required properties and methods. I would more think about the protocols as a template, where all of the required parts needs to be filled out. If we are referencing to a protocol in Objective-C, the form is used, where ProtocolWantToConform is the name of the protocol.

About the Delegation pattern

The delegation pattern originally was created for allowing something similar to multiple inheritance, which is not available in most of the programming languages. In our Apple software ecosystem the pattern is more about acting in behalf of another object. Usually delegates are for accomplish a well designed (and limited) functionality, helping the developers to have a nicely decoupled software. The best examples for the delegation patterns are the UITableViewDelegate and UITableViewDataSource protocols. With a careful software design you can use separate classes and code to provide the behavioural part (from the delegate) and the data source for your table view. The benefit to do so is that you can later easily change any of them, without making significant changes in the table view controller itself.

About the protocol files

Ok, I have already tried to explain what is a protocol, let see how can you create a protocol file. Don’t forget the protocol should stand only as a blueprint for the classes want to conform or implement to the protocol. Having said that we don’t need to implement any details in the methods, only the method signatures and optionally we can also specify if the method is optional.

Creating a protocol file is a bit tricky in Xcode, but you can used to it quite easily: Go to File -> New-> File, and on the screen select the Objective-C file (marked with a small m), as you can see on the screenshot below.

Click on Next and select “Protocol” as File Type, and give it a reasonable and meaningful name.

Eventually you will end up only one file, with the .h extension, and a quite simple @protocol NameOfProtocol @end structure in the file. Note, that is the parent or super protocol!

Protocol files for our solution

As we can see on the UML diagram, there are 2 protocol files used: PMODataHolder and PMODownloaderFromURL and in our specific case we need to establish a to way communication, or at least cross reference between those entities via the delegate and the receiver properties. Keep in mind, that we need the receiver property to hold the reference of the image holder object in the delegate protocol in order to make a callback on it with the downloaded data.


I think it is a well commented file. There are a few thing though which I would like to emphasise.
Please note the forward declaration of the cross referenced protocol for the delegate class, which was required by Xcode, to build the solution. Without this I had a nasty “No type or protocol named” error.
The second thing I want to emphasise is about the delegate property declaration. As you can see the delegate will be strong attribute. The other thing you should note, that the delegate type is id, and needs to implement the . This kind of declaration can make your code loosely coupled, since this declaration won’t tell you what kind of object we want to reference here, only we require that this class need to implement certain type of protocol. I think this is one of the important techniques which helps you to apply the principle from the GoF design patterns book, “Program to interfaces, not implementation”.


The only change here about the cross declaration is the weak attribute of the receiver property. This is because I would like to avoid from retain circles. Using the weak pointer means if the receiver object for some reason has been already deallocated (for example the download process takes long time, and the user has been already moved to another screen), the receiver object will be successfully freed from the memory by the ARC.

Changes in our files


As it was described in our new UML diagram, the PMOPictureController need to implement the PMODataHolder protocol. At //1 the protocol header file imported, and at //2 it is declared, that this class needs to conform the said protocol.

Take a look at the @synthesize at //1. If you remember I created a property in the protocol, but I also told, that the protocol file is just a blueprint, the developer’s work is to build a class from this blueprint. Unfortunately the properties, declared in the protocol won’t be automatically synthesised for us, that’s why we need to implement them: by synthesising them. In very simple terms this line creates a private variable in the class, called _delegate, which will be bound to the self.delegate property. It also creates the default accessors for the self.delegate. Make note about the initializer changes: it will set up the PMODownloader as a delegate immediately after the default initialization.

At //2 we just simply pass the task to our delegate, this is the part where actually the pattern implemented, ie. asking another class to do something in behalf our controller.

//3PMODataHolder protocol, including this method. I kept the other part of the class unchanged, so we still notified in any download problems, and the controller also notifies the objects, which are observing the image Key-Value change.

So, let’s take a look on our downloader class, how is the protocol will be implemented, and what has been changed:

At //1 I import the protocol file, so in the line at //2 I can use it, with the class declaration, that this particular class will implement the protocol. As you can see the forward declaration for - (void)downloadDataFromURL:(nonnull NSURL *)url; has been removed, since now it is declared in the protocol.


At //1 I use the same technique to synthesise the _receiver property, as it was used in the PMOPictureController.m.

Maybe you have already noticed that the code is getting more clear, and it is definitely seen in the method at //2, where all of the other calls just simply replaced by a callback to the receiver, and passing the downloaded raw data.

I also removed the other, now useless code, but I kept the one for notifying about the download failure.

Updated test cases

As I changed the strategy, how to carry out the download, actually hiding the downloader class behind the delegation pattern, our tests need to be updated as well.

As you can see, now our download test is based on a KVO on the PMOPictureController image property.

PMODownloaderTests .m

I removed the successful download test, since this part of the code should work via the delegation pattern.

Wrap up

I hope you could earn some knowledge from this post. Delegation is quite powerful, in terms of segregation of concerns, which leads us to clean(er) code. It needs some preliminary planning and design, by using “Program for interfaces, not implementation.” principle.

For that particular case, i.e. asynchronously downloading an image, delegation is not the best solution still. The last post of this series I will introduce the block based solution.