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

thread confinement

https://www.quora.com/What-is-Thread-Confinement

Thread confinement is the practice of ensuring that data is only accessible from one thread. Such data is called thread-local as it is local, or specific, to a single thread.

For example, declaring local variables is a form of thread confinement because each thread has its own local stack. The local variables you declare, are to be used for say thread A only. If another thread B comes in, it cannot use thread A’s local stack variables. Each thread has its own stack, and manipulates its own stack. This is called Thread local data.

Thread-local data is thread-safe, as only one thread can get at the data, which eliminates the risk of races. And because races are nonexistent, thread-local data doesn’t need locking. Thus thread confinement is a practice that makes your code safer (by eliminating a huge source of programming error) and more scalable (by eliminating locking).

An example of this would be a Servlet’s GET or POST method. In such a GET/POST method, if you were to declare local variables, these variables are to be confined to the specific thread that comes in. No other thread are sharing those variables.

Let’s say you declare member variable for the Servlet class. That member variable has global scope, and thus, can be shared by threads. This will lead to lots of problems, such as race conditions, or locking issues, and thus, we do NOT have thread confinement.

Core Data Stack #2 – 1 context, background task

  • http://www.cocoabuilder.com/archive/cocoa/290810-core-data-conflict-detection.html
  • http://joelparsons.net/blog/2013/09/02/background-core-data-with-privatequeuecontext

Updated Demo 5/5/2016

demo 10/26/2015

Have the context process in the background

First step is to add a private queue context where it will save a lot of data into the database.

  1. add a NSManagedObjectContext privateQueueContext object, synthesize it
  2. custom set method where we create the context with a queue
  3. queue up tasks such as bulk add
full source for CoreDataStack.h

addBulkPeople method is the process of using our privateQueueContext object and throwing a block on the queue and processing the saving of data into the database.

reportOnAllPeopleToLog method is using our mainQueueContext to simply get data from CoreData and see what’s in the database.

CoreDataStack.m

First, we set up our init method and init our queue contexts via custom setter methods.

Notice when we alloc and init NSManagedObjectContext, we initialize the context with concurrency type NSPrivateQueueConcurrencyType

Essentially, instead of the old way of attaching a context to a thread, we now have the option of attaching a context to a queue. This means that whatever job and/or tasks are lined up for this context gets queued. Thus, whatever operation needs to be done by that context will be completed FIFO via blocks.

Now that we have our queue context ready to be used, use queue up tasks by adding in blocks of code to the queue. We want to add a bulk of people so we queue up the task of “adding 10,000 people”. This is obviously a very time consuming task, and by adding it onto our context queue, we make it run in the background. Thus, freeing up the main thread for UI operations.

reportOnAllPeopleToLog

…simply reads the Core Data and displays the results.

Keep in mind that in the demo, the mainQueueContext is initialized with
NSMainQueueConcurrencyType, which runs on the main thread.

Thus, you SHOULD put tasks that update UI here.

If you are to use a time consuming task like a loop that displays all the People (like how we’re doing it), expect the main UI to freeze.

If you want to change it so that logging is done in the background and not freeze the UI, then change the NSMainQueueConcurrencyType to NSPrivateQueueConcurrencyType.

Then, put your code inside [self.mainQueueContext performBlock:^{…}.

Below are just some of the standard methods for the core stack.

Now, run the app. Make sure there is no previous version installed because we want a clean database.

Click on the add bulk button so we let it add 10,000 people into the database. Then play around with the scrollbar, you’ll notice that its responsive. Hence, we’ve successfully used the context to queue up jobs and run them on a background queue. The main thread is then responsive.

add_bulk

If you want to display all the Persons you’ve added, click on the display all button. The display all button uses the mainQueueContext, which runs on the main UI. Hence, put all the code that updates the UI, into that queue.

display_all

For demonstration purposes, we are using NSPrivateQueueConcurrencyType for the mainQueueContext. Hence, anything you do on on that context SHOULD BE TO UPDATE THE UI.

If you do labor intensive job such as logging all the People you’ve added, the UI will freeze…as demonstrated in the updated demo project.

IF you want to do the logging in the background, you can change it to NSPrivateQueueConcurrencyType:

then place your logging task in the performBlock like so:

Then, your logging will be executed in the background and not block the UI.

Next, using multiple contexts >>

Core Data part 4 – rollback

After you get an object and change its attributes, IF YOU DO NOT saveContext, you can rollback the data to its original value.

For example, say we get the first indexed Person object. You change the first name to Ricky. If you use [coreDataStack saveContext], that means the change is permanent in the database and you will be able to see the change when you restart up.

But if we comment out [coreDataStack saveContext], that means the change is not permanent and is only in cache context. You will see the change in the current usage of the app, but if you restart the app, you will see the old value.

In other words, in the database, we have NOT updated the value.

When [coreDataStack saveContext] is commented out, the changes you make is ONLY reflected in the current usage of the app, and not in the database. Thus, you can rollback to the original value by first checking to see if there was a change on the context by using
[[coreDataStack managedObjectContext] hasChanges]. Then if there was a change, you rollback the value by doing [[coreDataStack managedObjectContext] rollback]

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.

Add-Entity

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

Entity-Properties

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.

subclass-managed

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.

use-scalar-for-primitives

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:

Result:

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.

result:

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
(lldb)

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

When to use delegate, blocks, or notifications

http://stackoverflow.com/questions/21771606/objective-c-delegate-or-c-style-block-callback

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.

Retain cycle with Blocks in iOS

references
https://zearfoss.wordpress.com/2012/05/11/a-quick-gotcha-about-blocks/
http://stackoverflow.com/questions/14649661/defining-objective-c-blocks-as-properties-best-practice/14650386#14650386

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.

block-2

Code

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.

Solution

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

http://stackoverflow.com/questions/11168916/weak-or-strong-for-iboutlet-and-other

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.

MyProtocol.h

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

Child.h

Child.m

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.

Parent.h

Parent.m

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.

main.m

Result:

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..
(lldb)

The delegate Retain Cycle!!

main.m

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