Category Archives: iOS

Block basics

reference
http://stackoverflow.com/questions/22996536/resolving-retain-cycles-is-there-really-a-reason-to-add-strong-strongself-wh?rq=1
http://rypress.com/tutorials/objective-c/blocks

http://www.cocoawithlove.com/2009/10/how-blocks-are-implemented-and.html

demo xCode 7.3

How To Declare

Interface: We have the return type. Then block name. Then the parameters.

Then a equals sign, which leads to our declaration of the block. In the declaration of the block, be sure to name your parameters.

non-local variables are variables defined in the block’s enclosing lexical scope, but outside the block itself.

non-local variable are copied and stored with the block as const variable, which means they are read-only.

In other words, it creates “const” copy of any local variables that is referenced inside its scope.

Global Blocks – not referencing any non-local variables

With no references to the surrounding scope, clang configures the Block_literal as a global block instead.

For example,

If you’re familiar with how Objective-C objects are declared, the isa field in the Block_literal above should be familiar — blocks are Objective-C objects.

As you see, it does not reference any non-local variables. Thus, the compiler creates it as a global block:

global_block

This causes the block to appear in a fixed global location instead of on the local stack.

The implication of this is that global blocks are never actually copied or disposed, even if you invoke the functions to do so. This optimization is possible because without any references to the surrounding scope, no part of the block (neither its code nor its Block_literal) will ever change — it becomes a shared constant value.

Malloc Blocks – __strong block definitions

The block object was retained by the whisper variable. The strong sends a retain to the block. When a block is retained, it invokes a copy on it.

block implementation detail:

Thus, the block object was moved from stack to heap by this _Block_copy. But note that there is only still 1 copy of the block. It simply increases the retain count of the block.

malloc_block

Stack Blocks – __weak block definitions

http://stackoverflow.com/questions/25794306/could-you-help-me-to-understand-block-types-when-added-to-containers-nsdictiona

http://stackoverflow.com/questions/19227982/using-block-and-weak

Marking it as __weak causes the whisper variable to NOT retain the block object.
Thus, the block starts off being allocated on the local stack, and it stays there. Since there is no __strong to retain it, and thus, no copy.

therefore, a weak block variable on a block object keeps the block object on the local stack.

stack_block

If you copy an NSStackBlock, it will return an NSMallocBlock (indicating its changed allocation location).

A block keeps it’s own array of its non-local variables via deep copy

example:

So as you can see, the non-local variable make gets copied inside of the block getFullCarName. If you try to modify make inside of the block getFullCarName, you will see a compiler error.

Notice how later, outside of the block, we change the variable make to “BMW”. However, its a deep copy, this change takes place at the outside of the closure. Hence the original make variable (outside of the closure) is BMW. The copy inside the block, the make is still Honda. We see this happening by passing @”Civic” into getFullCarName(…).

You can make non-local changeable by using __block to use them as reference

Freezing non-local variables as constant values is a safe default behavior
in that it prevents you from accidentally changing them from within the block;
however, there are occasions when this is NOT desirable.

You can override the const copy behavior by declaring a non-local variable with the __block storage modifier:

This tells the block to capture the variable by reference, whereas if you didn’t have __block, it would capture it by deep copy.

When the block captures the variable by reference, its like creating a direct link between the variable outside the block and the one inside the block.
You can now assign a new value to make from outside the block, and it will be reflected in the block, and vice versa.

So now, you are referencing the same variable outside and inside the block. Whereas before, you have 2 deep copies of the variable depending on whether you are outside or inside of the closure.

Each block has its own copy of the non-local variables

In the example below, if we call existingBlock or vv twice, you will see that the non-blocking variables that they copy will have the same address. Their local variables, however, are all different throughout the calls. That’s because for the local variables of the block, they just go on the stack. Where as the outside scope’s variable are all copied….in an array for that particular block.

But what about Object allocations

As show in the code above, we have a block called vv. vv calls existingBlock block.
Then, say we have an object allocation outside of the block existingBlock at the highest scope at foo function.

We have 2 parts:

1) the reference ptrToStrObj gets pushed onto the local stack,
with address say: 0x7fff5fbff708

2) and the object that’s allocated on the heap, pointed to by reference ptrToStrObj. The object has address say: 0x100102450

block-1


LOCAL – address of POINTER ptrToStrObj……0x7fff5fbff708
LOCAL – address of NSString object on heap……0x100102450

The ptrToStrObj variable is a non-local variable, which means it defined in the block’s enclosing lexical scope, but OUTSIDE of the block itself. It is deep copied inside of the block.

We display the address of the the reference ptrToStrObj inside of the block existingBlock, which then shows:


———-existingBlock START ——
existingBlock – address of POINTER ptrToStrObj……0x1020001c0
existingBlock – address of OBJECT……0x100102450
existingBlock – ricky tsao, dob 6680
———-existingBlock END ——

As you can see, the address of the object on the heap remains at 0x100102450.
But the pointer of the reference ptrToStrObj has changed from 0x7fff5fbff708 to 0x1020001c0.

That is proof that the block made a deep copy of the non-local variable reference ptrToStrObj for itself.

Furthermore, if you try to modify ptrToStrObj, it will throw an error:

change-nonlocal-block

After calling existingBlock(), we move on to the next line:

changing content of string object
vv – address of POINTER ptrToStrObj……0x102000248
vv – address of OBJECT……0x100102450
vv – HA DO KEN!ao, dob 6680
———-vv END ——

Keep in mind that we are now back in bloc vv.

As you can see, the address of the object in the heap remains the same at 0x100102450.
However, the pointer address changed to 0x102000248. This means that this block vv has its own DEEP COPY of the non-local variable ptrToStrObj.

Thus,

foo’s ptrToStrObj is 0x7fff5fbff708
existingBlock’s ptrToStrObj is 0x1020001c0
vv’s ptrToStrObj is 0x102000248

In much deeper details, each block has an non-local variable array list. That’s where it keeps its list of non-local variables. As we can see in the picture vv block and existingBlock each have an array of non-local variables.

The first item in their array is reference ptrToStrObj. ptrToStrObj points to the object in the heap, which never changes as we can see that the addresses all match.

However the address of the references are different, because each block has their own DEEP COPY of the reference.

block-2

Finally, let’s see what happens inside of a GCD block:

THREAD 2 start
———-vv START ——
———-existingBlock START ——
existingBlock – address of POINTER ptrToStrObj……0x1020001c0
existingBlock – address of OBJECT……0x100102450
existingBlock – HA DO KEN!ao, dob 6680
———-existingBlock END ——
changing content of string object
vv – address of POINTER ptrToStrObj……0x102000248
existingBlock – address of OBJECT……0x100102450
existingBlock – HA DO KEN!N!ao, dob 6680
———-vv END ——
in dispatch_async block – address of POINTER ptrToStrObj……0x100500048
existingBlock – HA DO KEN!N!ao, dob 6680
existingBlock – address of OBJECT……0x100102450
THREAD 2 done

As you can see the object in the heap as address 0x100102450 for all blocks

existingBlock’s ptrToStrObj has 0x1020001c0
vv’s ptrToStrObj has 0x102000248
GCD’s ptrToStrObj has 0x100500048

Hence, as you can see, GCD’s block, like any other blocks, also have its own non-local variable list, and DEEP COPIES the non-local variable reference ptrToStrObj for itself.

Code

output:

LOCAL – address of POINTER ptrToStrObj……0x7fff5fbff7e8
LOCAL – address of NSString object on heap……0x100211f00
Stack: &x: 0x7fff5fbff7f8, 1
Stack: &x: 0x7fff5fbff7f4, 2
——- on main thread ——-
———-vv START ——
existingBlock – address of POINTER ptrToStrObj……0x1001001e0
existingBlock – address of OBJECT……0x100211f00
existingBlock – ricky tsao, dob 6680
———-existingBlock END ——
changing content of string object
vv – address of POINTER ptrToStrObj……0x100300378
existingBlock – address of OBJECT……0x100211f00
existingBlock – HA DO KEN!ao, dob 6680
———-vv END ——
THREAD 2 start
———-vv START ——
———-existingBlock START ——
existingBlock – address of POINTER ptrToStrObj……0x1001001e0
existingBlock – address of OBJECT……0x100211f00
existingBlock – HA DO KEN!ao, dob 6680
———-existingBlock END ——
changing content of string object
vv – address of POINTER ptrToStrObj……0x100300378
existingBlock – address of OBJECT……0x100211f00
existingBlock – HA DO KEN!N!ao, dob 6680
———-vv END ——
in dispatch_async block – address of POINTER ptrToStrObj……0x100300168
existingBlock – HA DO KEN!N!ao, dob 6680
existingBlock – address of OBJECT……0x100211f00
THREAD 2 done

More Examples

GCD: dispatch_async

Contrary to what’s usually believed, dispatch_async per se will NOT cause a retain cycle

Here, the closure has a strong reference to self, but the instance of the class (self) does not have any strong reference to the closure, so as soon as the closure ends, it will be released, and so no cycle will be created. However, sometimes it’s (incorrectly) assumed that this situation will lead to a retain cycle.

Syntax

Blocks are declared like so:

..and used like so:

This example declares a variable called simpleBlock to refer to a block that takes no arguments and doesn’t return a value

You can also combine the variable assignment, and definition:

Another Example

The (void (^)(void)) specifies that the parameter is a block that doesn’t take any arguments or return any values. The implementation of the method can invoke the block in the usual way:

Method parameters that expect a block with one or more arguments are specified in the same way as with a block variable:

it expects a block that does not return anything. But takes in double as the first 2 parameters.

Retain Cycle in iOS

ref – http://blog.reigndesign.com/blog/debugging-retain-cycles-in-objective-c-four-likely-culprits/
http://stackoverflow.com/questions/15266367/why-isn-t-my-weak-reference-cleared-right-after-the-strong-ones-are-gone?rq=1
http://www.quora.com/Objective-C-programming-language/What-is-the-difference-between-a-strong-and-weak-pointer

Pointers are automatically created with strong references; they are automatically retained. In this case, the strong keyword is implied when creating pointers, though you can use it if you want.

However there are times when you don’t want to retain an object (i.e. increase its reference count). To do this, you use the weak keyword when creating the pointer. Your pointer will still point to the object, but if that object is destroyed then using the pointer will cause a program error.

Note: In Objective-C every object has a reference count (i.e. the number of strong references to the object). i.e alloc, retain, new, dot retain,

In our case below, strongPtr points to newly allocated NSString object. Then it points away to another newly allocated NSString object. the original NSString object “myTestText” has no one pointing to it, even though it exists in memory because it does have a retain count of 1. Its just hanging out in memory space. Thus, ARC will either send a release or auto-release to it.

If ARC send release, weakPtr will display nil. If auto-release, then weakPtr may still display the address of the “myTestText”:

  • Strong variables will retain the value they point to.
  • Weak variables won’t retain their value and when the value is deallocated they will set their pointer to nil (to be safe).
  • Unsafe unretained values (as you probably can read by the name) won’t retain the value and if it gets deallocated they do nothing about it, potentially pointing to a bad piece of memory

When you’re working with garbage collection (10.5+), a weak reference is created by prefixing a variable declaration with __weak. When you assign to that variable, the GC (if enabled) keeps track of the reference and will zero it out for you automatically if all strong references to the referenced object disappear. (If GC is not enabled, the __weak attribute is ignored.)

Thus, you can safely modify the above answer to play nicer with garbage collection (currently on 10.5+, and perhaps someday on iPhone) as follows: (See the related Apple docs.)

@property (nonatomic,assign) __weak Row *yCoord;

To quote Chris Hanson (where you can find more detailed information):

“By prefixing an instance variable declaration with __weak, you tell the garbage collector that if it’s the only reference to an object that the object should be considered collectable.”

I’d clarify that by saying “if there are no non-weak references to an object”. As soon as the last strong reference is removed, the object may be collected, and all weak references will be zeroed automatically.

Note: This isn’t directly related to creating weak references, but there is also a __strong attribute, but since Objective-C object variables are strong references by default, it is generally used only for raw C pointers to things like structs or primitives that the Garbage Collector will not treat as roots, and will be collected from under you if you don’t declare them as strong. (Whereas the lack of __weak can cause retain cycles and memory leaks, the lack of __strong can result in memory stomping and really strange and insidious bugs that occur non-deterministically and can be quite difficult to track down.)

Why would you use a weak reference?

Well, one reason is if you have objects in parent-child relationships where the parent keeps pointers to its children and every child keeps a pointer to its parent. The potential with this structure is that you could no longer need your parent object and XCode will implicitly release it, but because its children keep a reference to it, the parent and its children can remain in memory even though you no longer have a way of accessing them. This is called a retain cycle.

To avoid the retain cycle, the children objects should only maintain a weak pointer to their parents. The reason for this is that when the parent is told to destroy itself, the children would be destroyed first so there is no chance they could access their parent after it had been destroyed.

NSTimer

If you create an NSTimer object on a view controller, be sure that invalidate is called on it when dismissing the view controller, otherwise it will retain self.

Observers/NSNotificationCenter

If you add an observer to NSNotificationCenter, make sure you remove all observers when dismissing the view controller, otherwise they will retain self.

Blocks

You should not call [self doSomething] from inside a block, this can easily lead to the block capturing a reference to self. Instead, make a weak reference to self:

BAD:

GOOD

Delegates

if you use

inside the view controller, check the delegate property on someObj is weak.

Once you’ve made your fixes, check that dealloc is getting hit and the allocations no longer increase endlessly.

when to use dispatch_sync

reference
http://stackoverflow.com/questions/4607125/using-dispatch-sync-in-grand-central-dispatch
http://stackoverflow.com/questions/9471420/whats-the-benefit-of-using-dispatch-sync-if-it-has-to-wait-until-the-main-threa?lq=1

First, let’s look at dispatch_async

You use dispatch_async to create a new thread. When you do that, the current thread will not stop.

That means:

Do More Stuff may be executed before Do something else finish.

What happens if you want the current thread to stop

You do not use dispatch at all. Just write the code normally

//Do something
//Do something else
//Do More Stuff

Now, say you want to do something on a DIFFERENT thread and yet wait as if and ensure that stuffs are done consecutively.

There are many reason to do this. UI update, for example, is done on main thread.

That’s where you use dispatch_sync

//Do something
dispatch_sync(queue, ^{
//Do something else
});
//Do More Stuff

Here you got

  1. Do something
  2. Do something else
  3. Do More stuff done consecutively

…..even though //Do something else is done on a different thread.

Usually, when people use different thread, the whole purpose is so that something can get executed without waiting.

An Example of using Dispatch_Sync

Say we have a mutable array.

We then create a custom queue q in order to take tasks to execute.

We throw some blocks on this custom queue q and process it via asynchronously via dispatch_async.

Now, say, we want to pull the first item off of the array. Then shift all the items over 1 spot to fill in the empty space. Hence, we’re rearranging all this data on the array….we can’t be letting other threads touch this array (i.e adding, deleting, updating…etc)

We gotta stop all activities on the queue that’s adding stuff to our array. That queue is q so we gotta synchronous on it.

We take off the 1st item like so:

We sync our taking off the 1st item with the other tasks in the queue. In other words, we make other tasks wait, execute taking off the 1st item, and let others continue.

Thus, this is an example of why we use dispatch_sync. We when we use sync, we block all other tasks on that queue. Let us finish our block. Then let the other tasks on that queue continue.

One More!

dispatch_sync does what you think — it posts the block to the nominated queue and blocks the current queue until the block has been performed. The main queue/thread isn’t specifically involved unless you’re either dispatching to it or from it.

So, you’d generally use it if an operation had to be performed on a different queue/thread — such as a SQLite or OpenGL operation — but you either needed the result of the operation or simply needed to know that the operation was complete for functionality terms.

The pattern:

is better practice but isn’t really something you can just glue on at the end.

@dynamic

Definitions

@synthesize will generate the getter and setter methods of the properties if the getter and/or setter has not already been implemented manually. This is what you currently believe @dynamic does.

@dynamic is used when you don’t want the runtime to automatically generate a getter and setter AND you haven’t implemented them manually. Basically, @dynamic is telling the compiler that the getter/setter will be provided dynamically at runtime or provided elsewhere, like a base class.

Usage

Since @dynamic means that the getter and setter methods are implemented elsewhere. One of the ways is to have runtime look for them in a Base class.

For example, say we have a Base class, and we implement the getter/setter methods like so:

When we use self.publicAge, we use the getter/setter properties generated by the compiler. If we want to manipulate the instance variable itself, we use _publicAge.

Same goes for publicName.

If we want to write our own customizable methods, we’d do:

In which case we over-ride the get/set methods generated by the compiler with our own custom get set methods. Whether you want to use the generated or your own custom methods is both fine, depending on your needs.

Using @dynamic

Now this is where using @dynamic comes in.

Say you have a class Child1, which is derived from the Base class.

@dyanmic means the getter/setter methods are implemented by the self class, but somewhere else
like superclass (Base), or be provided at runtime.

Hence when you use the properties

they will use Base’s publicAge and publicName getter/setter methods.

lazy loading pattern using property and synthesize

NSURLConnection and GCD

If you have a class that uses NSURLConnectionDataDelegate and does asynchronous work via the NSURLConnectionDataDelegate methods

do not pair it with GCD because it itself is a separate worker thread that does the connections for you. Hence use NSURLConnection async by itself.

If you use NSURLConnection sync version, then you can use it with GCD.

Passing array json to Server

iOS client

Basically, as we’re constructing our dictionary, our key is flowDates. We use an array of strings as our value.

Server side

The json packet comes to our server via the request object.

In the request object’s body, we use key flowDates to get the array of strings passed in from the iOS client. We loop through this flowDates array to get the strings.

While we loop, we create a temp object called flowDay with keys startDate and endDate, and enter the strings from the array flowDates as their value.

Then we push that object onto an empty array.

Finally, we use that array to create a new user:

Server side code