Monthly Archives: September 2015

Core Data part 3 – Add Data


Given that,

1) You have your Data Stack set up
2) You have a model set up, and generated your model object which derives from NSManagedObject. Make sure your properties are @dynamic so that it uses the superclass’s synthesis (via NSManagedObject).

Remember, if you do not use @dynamic, and instead use @synthesize, it means you will be writing the getter/setter method yourself and if you do not write it correctly, the data you save using Core Data will not be there when you restart the app.

for xCode 7 and after, category file is generated

If you are using xCode 7 or after, a category file is generated along with the entity file like so:

  • Person+CoreDataProperties.h
  • Person+CoreDataProperties.m
  • Person.h
  • Person.m

The reason for this is because whenever new entity files are generated by doing:

  • click on .xcdatamodeld file
  • then Editor >> Create NSManagedObject subclass

you won’t have your Entity files overwritten. All your properties and methods will still be there. Instead, xCode will over-ride the Category file(s) instead.

Hence put all your code in Person, and leave the Category file alone.

Implementing the Entity files



Adding data

In your CoreDataStack.h, we’ll make 2 methods.

  1. create a new person
  2. display on all the people who’s in the database into our console.

Here are the few important issues when Adding a Person using core data:

1) use insertNewObjectForEntityForName method for Core Data to return you a managed object so you can initialize it with data.

2) Make sure you save context on it.

Here are the few important issues when fetching using core data:
executeFetchRequest gets what we need according to a request. It returns an array and you can iterative through it and display it.

ViewController button and responder

In your UIViewController, add a button and a responder method for both Adding a Person and Logging all the people to the console

Now let’s add a display button. Give it a responder method name displayAll.

Implement the button responders:

Now, go ahead and run the project using xcode. Press the Add Person button to add Person objects into the database, and see the results through your console.

Then press the display button to show all the Person objects that’s been saved into the database. Restart the app using your xcode project, press the display button again, and look at the log console to see the objects you’ve saved from before.

Core Data – adding a data model

create the xcdatamodelid file

File >> New >> File

Under iOS >> Core Data >> Data Model

Select it and give it a name. Make sure you use this name in your core data stack’s code. This is so that it can load it into a MOM object successfully.

Click on .xcdatamodeld file to see your design. It comes in 2 styles. One is editor style, and the other is graph style.

Make an entity

Click on the plus sign to create an Entity and give it a name. In SQL terms, you created a table Person. In Core Data, we call it an Entity.


You can also check out the properties by opening the right pane. Then clicking on the properties icon.


Notice the Attributes. They are like the columns in a table. We declare names of the attributes and their type.

Add an attribute

Select the Entity name and under Attributes, click on the ‘+’ button. Give the attribute firstName, and select String as the Type.

Create attributes for firstName and lastName.

Now that we’re done with our model, we need to create an concrete class to represent our entity.

We are going to subclass NSManagedObject to represent our Person Entity.

Click on Entity, then menu Editor, and click on Create NSManagedObject subclass.


Click next on all the wizard pages until you reach the end. Make sure to check the box where it says use scalar for primitive types. This is so that it does not use NSNumber objects to represent your primitive values.


Dynamic Typing

Dynamic typing enables the runtime to determine the type of an object at runtime.

For example say we have this code:

This is a statically typed pointer. It declares that the variable myAtom is a pointer to an object of type Atom.

With static typing, the compiler performs type checking, and thus detects type errors.

With dynamic typing, type checking is performed at runtime. It is done via the id data type.

The id type is a unique Objective C type that can hold a pointer to any type of Objective C objects.

Therefore, the variable myAtom can point to any NSObject.

  • Dynamic typing permits associations between objects to be determined at runtime, rather than forcing them to be encoded in a static design.
  • Dynamic typing also gives you much greater flexibility because the types used by a program can evolve during its execution and new types may be introduced without the need to recompile or redeploy.

For example, the method can take any object:

We can also specify that whatever object we pass in must conform to protocol NSDecimalNumberBehaviors

Or, we can specify that the object type must be NSNumber

Or, that the type must be type NSNumber which conforms to protocol NSDecimalNumberBehaviors

SEL and method signatures

To summarize, the following are the key elements of Objective-C object messaging:

  • Message: A name (the selector) and a set of parameters sent to an object/class.
  • Method: An Objective-C class or instance method that has a specific declaration comprised of a name, input parameters, a return value, and the method signature (the data type(s) for the input parameters and return value).
  • Method binding: The process of taking a message sent to a particular receiver and finding and executing the appropriate method. The Objective-C runtime performs dynamic binding of messages to method calls.

The Objective-C runtime uses selectors to retrieve the correct method implementation for a target object/class.

selector type is a special objective type that represents a unique identifier that replaces a selector value when the source is compiled.

Given that sumAddend1:addend2: method exist in class Calculator:


2015-09-25 08:39:25.616 RunTime1[3929:383317] Hello, World!
2015-09-25 08:39:25.617 RunTime1[3929:383317] 1
2015-09-25 08:39:25.617 RunTime1[3929:383317] 2
2015-09-25 08:39:25.618 RunTime1[3929:383317] sumAddend1:addend2: with 25 10
2015-09-25 08:39:25.618 RunTime1[3929:383317] 3
2015-09-25 08:39:25.618 RunTime1[3929:383317] Sum of 25 + 10 = 35

But what if we have a method signature that does not exist, say sumAddend1:addend25:?

You will get a SIGABRT error. Your code will also exit right at

with a Thread 1:signal SIGABRT error.

The rest of your code will not be executed.


2015-09-25 08:18:11.524 RunTime1[3897:378030] Hello, World!
2015-09-25 08:18:11.525 RunTime1[3897:378030] 1
2015-09-25 08:18:11.525 RunTime1[3897:378030] 2
2015-09-25 08:18:11.525 RunTime1[3897:378030] -[Calculator sumAddend1:addend25:]: unrecognized selector sent to instance 0x100101af0
2015-09-25 08:18:11.617 RunTime1[3897:378030] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[Calculator sumAddend1:addend25:]: unrecognized selector sent to instance 0x100101af0’
*** First throw call stack:
0 CoreFoundation 0x00007fff8aa77bd2 __exceptionPreprocess + 178
1 libobjc.A.dylib 0x00007fff86f36dd4 objc_exception_throw + 48
2 CoreFoundation 0x00007fff8aae10ed -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x00007fff8a9e83d1 ___forwarding___ + 1009
4 CoreFoundation 0x00007fff8a9e7f58 _CF_forwarding_prep_0 + 120
5 RunTime1 0x0000000100000afa main + 282
6 libdyld.dylib 0x00007fff980215ad start + 1
libc++abi.dylib: terminating with uncaught exception of type NSException

In order to avoid this, use try/catch/finally so that it will simply throw an exception and keep your code moving.

Also, notice because there was an error at performSelector due to a non-existent method signature, the rest of the try code block was not executed from NSLog 3 and on.

We go straight to the exception/finally code blocks, then continue on to the rest of the code after the try/catch/finally block.

2015-09-25 08:44:45.987 RunTime1[3952:385189] Hello, World!
2015-09-25 08:44:45.988 RunTime1[3952:385189] 1
2015-09-25 08:44:48.275 RunTime1[3952:385189] 2
2015-09-25 08:44:48.276 RunTime1[3952:385189] -[Calculator sumAddend1:addend25:]: unrecognized selector sent to instance 0x100100c60
2015-09-25 08:44:48.278 RunTime1[3952:385189] 4 – after performSelector fails, jumps straight to here
2015-09-25 08:44:48.278 RunTime1[3952:385189] Exception!!! -[Calculator sumAddend1:addend25:]: unrecognized selector sent to instance 0x100100c60
2015-09-25 08:44:48.278 RunTime1[3952:385189] 5
2015-09-25 08:44:48.279 RunTime1[3952:385189] finally!
2015-09-25 08:44:48.279 RunTime1[3952:385189] 6
2015-09-25 08:44:48.279 RunTime1[3952:385189] the rest

Custom TableView Cell

Create the TableView

First, we create a tableView member variable in our ViewController

Second, we declare its property, and synthesize

Then in the viewDidLoad, we allocate for the tableView and add it to the view hierarchy.



We now have an empty table. However, it doesn’t do anything because we need to conform to the UITableViewDataSource to let it know what kind of data it should have and display.

Conforming to UITableViewDataSource

We need to modify the table to our liking by working with its data source delegate methods. We first make it our ViewController conform to the UITableViewDataSource delegate:

Make sure you assign the dataSource

After declaring the protocol, you’ll get warnings to implement the required methods:

Implement the required numberOfRowsInSection method. We say we want 8 rows

Implement the required cellForRowAtIndexPath method. We tell the delegate that we want to draw our cell like standard but with certain text:



Creating the Custom Cell

First, create MyCustomTableCell class:



In your UIViewController, let’s change the cellForRowAtIndexPath method so that it takes our custom cell:



getting location of core data sqlite file

Then, copy it.

Open up finder, and press command + shift + g. A location window will pop up and paste the copied path into it. Press enter, and you’ll see the .sqlite file

When to use delegate, blocks, or notifications

Delegates should be used when there are multiple “events” to tell the delegate about and/or when the class needs to get data from the delegate. A good example is with UITableView.

A block is best used when there is only one (or maybe two) event. A completion block (and maybe a failure block) are a good example of this. A good example is with NSURLConnection sendAsynchronousRequest:queue:completionHandler:.

A 3rd option is notifications. This is best used when there are possibly multiple (and unknown) interested parties in the event(s). The other two are only useful when there is one (and known) interested party.

ARC is not a garbage collector!

ref –

There is no garbage collection with ARC, so there is nothing to call. If you control the scope and ownership of your objects, ARC will look after the memory use for you.

Apart from assigning ‘nil’ to a reference or letting the reference go out of scope, the only other consideration is whether you have some extra reference to the object (such as putting it into a NSArray) that has it’s own need to retain the object.

Note: An object pointer (or reference) gets pushed onto the stack. When you go out of your scope, that references gets popped, thus essentially nil-ing it.

Or in other words, pointing the reference away from the object on the heap, and thus making a -1 on that object. When that object has NO strong references to it anymore, it’s dealloc will be called.

Retain cycle with Blocks in iOS


First, please read Block Basics

But why do we use copy to keep the Block around?

By default blocks are created on the stack. Meaning they only exist in the scope they have been created in. This is an optimization, since stack allocation is much cheaper than heap allocation.

Stack allocation means that, by default again, a block will cease to exist when the scope in which it is declared exits. So a block property with retain semantics will result in a dangling pointer to a block that doesn’t exist anymore when the stack gets popped.

But How?

To move a block from the stack to the heap (and thus give it normal Objective-C memory management semantics and an extended lifetime), you must copy the block via [theBlock copy], Block_copy(theBlock), property copy, using GCD via dispatch_ which copies your block, etc. Once on the heap, the block’s lifetime is managed.

That’s why you need to declare block properties with copy so the block is copied when the property is set. Thus, avoiding a dangling pointer to a stack-based block.

Therefore, if you want to access the block(s) later they have to be copied to the heap by sending a copy message to the block object. ARC will do this for you as soon as it detects a block needs to be accessed outside the scope its created in.

Behind the scene, block implementation consist of a data structure containing the values of the variables used in the block. What this means is that if you declared non-local variables will be in the data structure. Thus when you use those non-local variables, you are using the ones you’ve added onto the data structure.

For example if you have a string literal “ricky”, or a int 5, the block will create these non-local variables unto its own data structure. Thus every block has its own data structures, and contains its own non-local variables.

You can see an example here

In addition, when you have a pointer to an Object allocated on the heap, that data structure adds a new pointer, and that new pointer points to the same object in the heap.



For further info, please read Block Basics

Retain Cycle on Blocks

consider this piece of code in a UIViewController. Basically, the UIViewController has a strong reference to a TapBlockView object.

Once we use self within the block, TapBlockView object then has a strong reference back to the UIViewController. Thus, the 2 objects both have a strong reference to each other…creating a retain cycle.

The reason why is because whenever a block uses a non-local variable (in our case, self), it deep copies the reference. Since self is a pointer to the UIViewController object, the block deep-copies the self pointer variable and places it in its data structure. The deep copied pointer strongly points to the UIViewController that’s in the heap.

Thus, now you have 2 situations which results in retain cycle:

1) you have a strong pointer in the block’s data structure pointing to the self object in the heap.
2) By using tapBlockView (or self.tapBlockView), UIViewController strongs it. Remember, by default, Even if you don’t use self.——, the default behavior for variables is __strong.


First, let’s set the solution up with this tidibit: Whatever pointer variable you declare INSIDE of the block, that means it gets pushed onto the local stack of the block.

Thus when the block is done, that local stack gets popped. Thus, if we were to use a strong reference and point it to whatever, when the block’s local stack gets popped, that strong reference will be nil-ed.

Part 1 – Use a weak reference to self. The weak reference promises that this block will not hold onto self. Basically, a __weak pointer will be put into the block’s data structure to be pointed to self. If and when self gets dealloc-ed, this block will not be holding on to it.

BUT! What if right we’re using the block, and the self object gets de-allocated?

Our block will be accessing bad data because we only have a weak reference to self. So in order to hold onto self just long enough for our block to do its processing….

Part 2 – our trick is to create a local strong reference to hold onto the weak reference that’s on the block’s data structure. Local strong reference pointers simply gets pushed onto the block’s local stack frame.

That way, when the block starts to process, there’s a strong reference to the self object. Hence self will never be dealloc’ed. Once the block finishes, its local stack will be popped, and thus, the strong reference will be nil-ed. Therefore, the block will only have a weak reference in its data structure that points to self. As a result, self can be dealloc’ed because there is no strong reference to it.

The main idea here, is to get a local strong pointer, and point it to a non-local weak pointer.
This accomplish 2 things:

1) The non-local weak pointer to the self variable (which gets deep copied onto the block’s data structure), prevents a retain cycle

2) The local strong reference to that weak pointer, prevents the self object from being deallocated before or during our block’s usage.

Delegate retain cycle in iOS

When a parent has a reference to a child object, you should use a strong reference. When a child has a reference to its parent object, you should use a weak reference or a unsafe_unretained one (if the former is not available). A typical scenario is when you deal with delegates.

First, let’s set up a protocol called TaskDelegate. It basically is a protocol for a parent, guardian, or whatever person that is in charge of taking care of the child. We require the guardian to be able to feed the child and bathe it.


Second, we create a Child Object with a delegate that strong references a class (Parent, Guardian,…etc) that conforms to the protocol TaskDelegate. Hence we use id because we don’t know whether it will be Parent class or Guardian class or CareTaker class or whatever. As long as it conforms to the Protocol, then we’re fine. See //1

We have methods that represents the action of the Child. Specifically, the child gets hungry. We represent that by the method gotHungry.

When that action happens, gotHungry checks to see if the delegating class of either Parent, or Guardian, or CareTaker, or whomever, can respond to the method feedIt. This method should feed our Child. If it does, then we call it. See //2



So create a class called Parent. This Parent conforms to protocol, so hence it can take care of the Child. It creates that Child object in its init method using a strong reference. This is standard..just like how in UIViewController’s viewDidLoad, you’d often see UI objects being created, then assigning that UI’s delegate to self…which then the UIViewController must conform to.

In the same way, our Parent creates a Child object. Assigns the Child delegate to self because it conforms to the Child’s delegate.



1) Finally we are able to use our delegate. We have a Parent who creates (or strong references a Child Object) in its init method.

2) When the child got hungry, it delegates a task to the Parent object. Then you’ll see that the Parent feeds it.

3) Let’s say the Parent needs to take a vacation from this program of taking care of its kid and leaves. So we nil the parent, and ARC garbage collects it. Because the Child’s delegate is weak, it will then be set to nil when the Parent Object gets deallocated.

4) you’ll see that the Child’s delegate then will be set to nil. It can be set to another Object that conforms to TaskDelegate later…such as if we decide to create a Nanny or Guardian object so that they can feed or bathe the Child.



2015-09-11 10:12:34.144 RetainCycleEx[68141:1785252] Child.m (init) – init
2015-09-11 10:12:34.145 RetainCycleEx[68141:1785252] Parent.m (init) – init
2015-09-11 10:13:05.141 RetainCycleEx[68141:1785252] Child.m – I’m HUNGRY! whoever is taking care of this child (delegate) gots to feed it!
2015-09-11 10:13:05.141 RetainCycleEx[68141:1785252] Child.m – Yup, this guardian (or parent) can feed
2015-09-11 10:13:05.142 RetainCycleEx[68141:1785252] Parent.m – shoves baby food into child’s mouth
2015-09-11 10:13:06.012 RetainCycleEx[68141:1785252] Parent.m – I’m dealloc…
2015-09-11 10:13:06.759 RetainCycleEx[68141:1785252] Child object’s delegate 0x0
2015-09-11 10:13:08.956 RetainCycleEx[68141:1785252] Child.m – I’m dealloc..

The delegate Retain Cycle!!


In order to create a retain cycle, the Child object can changes it delegate from weak to strong like so:

Thus, when we run main.m we create a Child, assigns the Child to a Parent, Child gets hungry, Parent feeds it. Very standard.

When the Parent gets niled, ARC doesn’t send dealloc to Parent because child’s delegate is strong and is referencing the Parent. And because Parent is not dealloc’ed, then it will never nil the objects that it may own. In our case, the parent strong references the Child and own it, thus, it will never dealloc that Child.

Hence, the Child and Parent both do not get dealloc’ed and thus is forever floating in memory.

That’s why when you run the code, you’ll see that the dealloc of Parent is never called and thus Child’s dealloc will never be called…and that the Child’s delegate to its Parent still shows a valid Object address.:

2015-09-11 10:41:51.695 RetainCycleEx[69880:1794099] Child.m (init) – init
2015-09-11 10:41:51.696 RetainCycleEx[69880:1794099] Parent.m (init) – init
2015-09-11 10:41:54.587 RetainCycleEx[69880:1794099] Child.m – I’m HUNGRY! whoever is taking care of this child (delegate) gots to feed it!
2015-09-11 10:41:54.587 RetainCycleEx[69880:1794099] Child.m – Yup, this guardian (or parent) can feed
2015-09-11 10:41:54.587 RetainCycleEx[69880:1794099] Parent.m – shoves baby food into child’s mouth
2015-09-11 10:41:55.659 RetainCycleEx[69880:1794099] Child object’s delegate 0x1003003d0