Category Archives: C/C++/Objective-C

VIPER Part 1 – Dependencies, Root Wireframe, AppDelegate, ViewController

demo for xCode 7.3

This tutorial shows how to hook up an AppDelegate, Dependencies object, a Root wireframe, and a standalone ViewController in a VIPER design pattern.

AppDelegate.h

Standard AppDelegate with the window property.

AppDelegate.m

AppDelegate allocates a Dependencies object. That dependencies object will then install a RootViewController onto the Window object.

Dependencies

The dependencies component has a property wireframe. This wireframe is what carries the logic of showing which ViewController. The ViewControllers are simply instantiated and used by the wireframe.

AppDependencies.h

The installRootViewControllerIntoWindow method simply passes along the window object, and let’s other wireframes (or itself) set view controllers on the window

AppDependencies.m

We simply instantiate a ViewController, and then passes it along into the RootWireFrame object so it can do its logic of showing which controller in the window

Wireframe carries logic of showing ViewControllers/Views

RootWireFrame.h

RootWireFrame.m

Using protocols to have components talk to each other in iOS Design Pattern

https://www.objc.io/issues/13-architecture/viper/

Protocol is a one to one relationship where a receiving object implements a delegate protocol. A sending object uses it and sends messages (assuming that those methods are implemented) since the receiver promised to comply to the protocol.

First, the Interactor protocol!

The interactor is the middle man between data and the presenter. It has a protocol that says

1) there is an input property from the presenter that forces Interactor to implement findUpcomingItems ( to find upcoming certain (decided by presenter) items or data.

2) there is an output property pointing to presenter that forces Presenter to implement foundUpcomingItems:.

InteractorIO.h

present_interact

Presenter.h

Presenter.m

Using the interactor property to force the Interactor component to implement required method(s)

The interactor property is connected to the Interactor component. Our interactor property (which conforms to InteractorInput), promises that this Interactor component will have the method findUpcomingItems implemented. Thus, say when we want to update the view, we tell the interactor component (through our id interactor property) to call the findUpcomingItems method.

In other words, Interactor can retrieve data for us because it talks to the DB Manager/Entities, thus, we (the Presenter) have an interactor property to the Interactor object so that we can call required Protocol methods to find certain data for us by forcing the Interactor component to implement findUpcomingItems:

Presenter component implements promised required protocol methods

Presenter conforms to InteractorOutput because we promise to implement a method foundUpcomingItems: which means we’ll take care of
the data returned by the Interactor.

The Interactor will point a output property to the Presenter. Thus, the output says Presenter must implement foundUpcomingItems:.

Interactor.h

The Presenter object works with the UIViews/UIViewControllers to display data, thus, we point an output property to
the Presenter object in order to force it to implement foundUpcomingItems:(NSArray*).

The method gets gets the found data
in Presenter, and thus, can have the UIViews/UIViewControllers display it.

Interactor.m

Interactor conforms to InteractorInput, which means we promise to implement a method called findUpcomingItems.
This is be requested by the Presenter/Views throug Presenter’s interactor property.

Hooking it all up

Binary Search Tree

http://code.runnable.com/VUTjJDME6nRv_HOe/delete-node-from-bst-for-c%2B%2B

demo download xCode 7.3 (c++)

Adding to Tree Concept

Traverse until you hit a leaf. Then, Re-point at the leaf

Finding from Tree Concept

Traverse if data does not match. If at leaf, return NULL.

1) we need the node back, hence, we return our traversals.
2) When we find our target node, we return a new Node with that value. That return will return traverse back.
3) If nothing is found then we return NULL.

Running Time

Average Time

Access: O(log(n))
Search: O(log(n))
Insertion: O(log(n))
Deletion: O(log(n))

Worst Time (due to unbalanced tree that deteriorates to a linear tree

Access: O(n)
Search: O(n)
Insertion: O(n)
Deletion: O(n)

The Node – building block of the Binary Search Tree

First we must create the building block of the tree. It is an object with a data container, a left pointer, and right pointer. Each pointer denotes a leaf.

You can initialize this object by value, and set both leafs to NULL.
Or you can pass in data to set everything.

Creating a BST tree

First we create the BST class. The key thing here is to add a private member for the root Node. This is the starting point of all tree manipulations.
Then we add the void addNode(Node * root, int newVal) for adding data algorithm.

Adding Nodes O(log n)

We start at the root node, and check the value of it with the incoming new value.

If the new value is larger than the root, then:

1) If the right node exist, we move down the right side of the tree via recursion.
2) If the right node is NULL, we create a new Node, and point it to the right node.

If the new value is smaller or equal than the root, then:

1) If the left node exist, we move down the left side of the tree via recursion.
2) If the left node is NULL, we create a new Node, and point it to the left node.

http://stackoverflow.com/questions/9456937/when-to-use-preorder-postorder-and-inorder-binary-search-tree-traversal-strate

Depth First Search – Pre order (left side)

print
recursion left
recursion right

If you know you need to explore the roots before inspecting any leaves, you pick pre-order because you will encounter all the roots before all of the leaves.

Depth First Search – Post order (right side)

recursion left
recursion right
print

If you know you need to explore all the leaves before any nodes, you select post-order because you don’t waste any time inspecting roots in search for leaves.

Depth First Search – In order (bottom side)

recursion left
print
recursion right

If you know that the tree has an inherent sequence in the nodes, and you want to flatten the tree back into its original sequence, than an in-order traversal should be used. The tree would be flattened in the same way it was created. A pre-order or post-order traversal might not unwind the tree back into the sequence which was used to create it.

Search for a value O(log n)

Search a value in the binary tree is the fastest. The time is O(log n).

If the node is not NULL, we recursively go down the tree according to if the “to get” value is larger or smaller. Then when we hit a node value that matches, we just return the current node.

Deletion O(log n)

Deletion is O(log n + k).

Delete All Nodes

The idea behind deleting all the nodes is a thorough recursion through the left and right.

We delete in 2 situations:

1) delete the node if it has no children
2) delete the node after left and right recursion.

given that if a root is NULL, we just return.
If a node has one child (and the other is NULL), then the NULL leaf just returns.
We recurse down the child.

BST.cpp

Testing it all

Stack based Memory Allocation

https://en.wikipedia.org/wiki/Stack-based_memory_allocation

http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap?rq=1

Stacks in computing architectures are regions of memory where data is added or removed in a last-in-first-out (LIFO) manner.

In most modern computer systems, each thread has a reserved region of memory referred to as its stack. When a function executes, it may add some of its state data to the top of the stack; when the function exits it is responsible for removing that data from the stack. At a minimum, a thread’s stack is used to store the location of function calls in order to allow return statements to return to the correct location, but programmers may further choose to explicitly use the stack. If a region of memory lies on the thread’s stack, that memory is said to have been allocated on the stack.

Because the data is added and removed in a last-in-first-out manner, stack-based memory allocation is very simple and typically faster than heap-based memory allocation (also known as dynamic memory allocation). Another feature is that memory on the stack is automatically, and very efficiently, reclaimed when the function exits, which can be convenient for the programmer if the data is no longer required. If however, the data needs to be kept in some form, then it must be copied from the stack before the function exits. Therefore, stack based allocation is suitable for temporary data or data which is no longer required after the creating function exits.

Parent class creating Child Class Instance

http://stackoverflow.com/questions/8916351/objective-c-alloc-child-class-from-parent-and-use-parent-class-instance-varria

demo

The Problem

The problem started when I was looking at NSURLSession’s dataTaskWithRequest:theRequest method.

dataTaskWithRequest returns an instance of NSURLSessionDataTask, which is a child class of NSURLSession.

Usually, in objective c, a class has an address. It instantiates another object (in the heap), which has a different address.

But how does a parent class return an object of a child class? The child’s parent class is the calling parent? or a different parent?

Basically, it works like this.

Explanation

Create a parent class. Then create a child class. If you were to instantiate the child class, the whole hierarchy sits on one address. Print out the address of self in both the init methods for Parent/Child. You will see that they are the same.

Parent .h/.m

Child .h/.m

What this means is that if you were to instantiate a child with an address, the parent (grand parent, grand grand parent…etc) class all sits on top of the child class. They are all ONE object, that takes up ONE address.

However, say in your parent class, you instantiate a child class. How would this work?

parent-child

The parent (with its own address of 0x1001072f0) instantiates the child class (with its own address 0x100400080) in the heap.

That itself should tell you that we are dealing with 2 separate objects here. If the child accesses its parent properties, it would be doing so in its OWN parent. (The parent that sit on top of the child) The parent that shares the same address with the child.

IF you want the child to access the calling parent, simply pass in the calling parent as a parameter.

So what’s up in NSURLSession’s dataTaskWithRequest

Hence, this is what’s happening when I see NSURLSession call a method, and returns a child class object.

inside dataTaskWithRequest, its creating a child class NSURLDataSession on the heap, which its own NSURLSession parent. They both sit on another address. This other object will process the request, then return execution to the completion block.

mutex vs semaphore

http://stackoverflow.com/questions/62814/difference-between-binary-semaphore-and-mutex

https://en.wikipedia.org/wiki/Race_condition

Mutex:

Is a key to a toilet. One person can have the key – occupy the toilet – at the time. When finished, the person gives (frees) the key to the next person in the queue.

Officially: “Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section.” Ref: Symbian Developer Library

(A mutex is really a semaphore with value 1.)

Semaphore:

Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count – the count of keys – is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.

Officially: “A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore).” Ref: Symbian Developer Library

Custom UIPickerView example

pickerview_custom

ref – http://stackoverflow.com/questions/3061401/respondstoselector-not-found-in-protocols

CustomPickerEx

Description

We are going to create a custom UIPickerView. This Picker View get the string of your selection, then send the delegating class the result. Hence a UIViewController can create this custom class, conform to the protocol, connect the delegate, and start receiving strings of the selected entries in the picker view.

Create class and override

Implement the protocol, create the delegate

For our case, we are going to create a single delegate which forces the UIViewController to implement our single delegate’s methods.

All default UIPickerViewDelegate and UIPickerViewDataSource will delegate to our custom RTPickerView.

If you want to group your custom delegate methods along with UIPickerViewDelegate, UIPickerViewDataSource, under RTPickerDelegate, you can declare it like so:

In your ViewController, when you conform to RTPickerDelegate
and you go self.pickerView.delegate = self,

Then you will be receiving all messages from all delegates.

However, for the sake of demonstration, we are going to create a custom protocol. When the ViewController uses it, it can receive 2 delegates. One is ‘delegate’ from UIPickerViewDataSource and UIPickerViewDelegate. One is RTPicker_Delegate, which is for taking care of our custom protocol methods.

That way, you can pick and choose which protocol you will want to conform to.

The RTPicker_Delegate delegate that we want our calling UIViewController to access should be weak. It should not be strong because as an object, we don’t want the controlling UIViewController to keep us in memory.

Implementation

Our Custom object conforms to View Delegates and Data Source delegates. Thus, we
take care of these protocol in this class. The calling ViewController is welcome to access the delegate property, and then implement these protocol methods too if it wants.

UIPickerViewDataSource methods

UIPickerViewDelegate protocol methods

RTPickerDelegate protocol method

When we are processing didSelectData, we don’t want the calling UIViewController to suddenly disappear on us. Thus, we strong ViewController temporarily. The local stack has a strong pointer on it, it makes the delegated UIViewController process messages, and this method will finish. Our strongDelegate is declared on the stack, and thus, will pop. Free-ing this class from the UIViewController

How to Use

Conform to the protocol

Create the object, make sure you add it to the UIViewController, and then connect the delegate. After connecting the delegate, all messages from that particular action which triggers the protocol method, will be sent to the ViewController for answers. You, as the developer of the UIViewController will need to implement it.

Implementation of the protocol method