All posts by admin

attach functions to objects

First declare your objects

Then you declare a function…

You can literally attach functions to objects like so:

Where the function uses ‘this’ to access the calling object’s attributes.
Using them like this:

would give:

name is: gary, age is: 25
name is: ricky, age is: 35

Closures (js)

http://javascriptissexy.com/understand-javascript-closures-with-ease/
https://medium.freecodecamp.org/whats-a-javascript-closure-in-plain-english-please-6a1fc1d2ff1c
http://ryanmorr.com/understanding-scope-and-context-in-javascript/

Udemy Example

When I invoke function greet, I’m gunna get a reference to another function, in which I can invoke again.

at 1), greet was invoked, so it was pushed then popped from the execution stack.

at 2) when you invoked the returned function object, it still can access variable ‘whattosay’. How is this possible?

First we have the Global Execution Context.
When greet function was invoked, greet() Execution Context was pushed.

The variable that was passed to greet() is sitting in that Execution Context.

We all know that every execution context have memory space reserved for variables and what not. When the execution context gets popped, the memory space presumably also leaves. The JS engine would eventually garbage collect it. However, in our case, in the creation phase of greet()’s context, the variables ‘whattosay’ and the return anon function were stored in memory. The return anon function is a function definiton, and as with any function defintiions, it gets stored in memory.

We invoked sayHi, which is the anon function in memory.
sayHi() Execution Context is pushed onto the context stack.
It runs through the function and are able to use variable ‘whattosay’ because it’s referencing the object that’s existing in memory.

This phenomenon is called ‘the Execution Context has closed in on its outer variables’. It has captured them.

Closure in Memory

Let’s explain the same code, but we’re going to use async capabilities, instead of a returned function.
We start with the same code.

In the very beginning, we set up the basic. We invoke the global context.

Global (Creation Phase) – which sets up its this, outer references, greetings definition, all in memory

Global (Execution Phase) – During the execution phase, go line by line and execute each line. We first see the function definition greetings. Its already in memory so we skip it. We step and then invoke greetings function. When invoking the function it creates a context, which we push onto the context stack.

Greetings Context (Creation Phase) – we put variable name into memory and assign it to undefined. We set the ‘this’ reference to the global object, and reference to the outer environment

Greetings Context (Execution Phase) – Now comes the line by line execution. Variable name points to immutable literal string ‘ricky’.
Then it invokes setTimeout function. setTimeout function is an async function so it gets put in memory.

Since the setTimeout function was invoked, it needs to go through creation phase and execution phase.
In the creation phase, it sets up the ‘this’ and outer reference for setTimeout. Then it sees the function definition in the first parameter. It puts that anonymous function in memory.

1) For setTimeout’s execution phase, it starts on the “2 second wait”. Once it starts, we continue on to the next step, which is the end of greetings function.
2) The end of greetings function signals that we pop greetings context from the execution stack.

1) Finally, the two seconds are up.
2) setTimeout executes its callback. It invokes the anon function. Thus, it gets pushed onto the context stack.
3) setTmeout completes and thus, gets removed from memory.

then,

1) The invocation of the anon function goes through its Creation Phase. There’s literally nothing there except a log. However, we see that in the log, we are referencing name variable from the memory.
2) We print the log statement
3) the anon function now finishes is popped off the context stack.

In the end, only the global context is left. In memroy, since nothing else is using name, nor anon function in this context, they will be garbage collected.

What is a closure?

Closure is the act of capturing an object and separating it from its original scope, making it available to the capturing function forever.

First off, you create a closure whenever you define a function, NOT when you execute it.

In other words, a closure is formed when a nested function is defined inside of another function, allowing access to the outer functions variables.

For example,

returning the inner function allows you to maintain references to the local variables, arguments, and inner function declarations of its outer function

This encapsulation allows us to:
1) hide and preserve the execution context from outside scopes
2) while exposing a public interface and thus is subject to further manipulation.

setTimeout example

First Try…

We’re accessing the i from the outside scope’s for loop via parent scope.

The result is:

0
1
2
3
4
5
6
7
8
9

1 second later…

10
10
10
10
10
10

not really what we want…

2nd try

We wrap an IIFE around it so that we save the index variable. Now, for each setTimeout invocation at each index i,
we have successfully saved i into parameter index. Each Execution Context is pushed on with the index variable.

Then the setTimeout inside will be able to access the index variable.

for loop: 0
for loop: 1
for loop: 2
for loop: 3

AFTER 3 SECONDs…

callback: 0
callback: 1
callback: 2

One of the most popular types of closures is what is widely known as the module pattern; it allows you to emulate public, private, and privileged members:

Module Pattern

The module acts as if it were a singleton, executed as soon as the compiler interprets it, hence the opening and closing parenthesis at the end of the function. The only available members outside of the execution context of the closure are your public methods and properties located in the return object (Module.publicMethod for example). However, all private properties and methods will live throughout the life of the application as the execution context is preserved, meaning variables are subject to further interaction via the public methods.

or executed in the context of the window object:

The closure has three scope chains

– it has access to its own scope (local variables)
– it has access to the outer function’s variables (including parameters)
– and it has access to the global variables.

When you put a function in a variable like this, you are assigning the variable func, a reference to the function sayHello, NOT A COPY.
Via definition of a reference, anything you do on the func reference will be done on the original function.

For example, when we add a property to reference func:

our function sayHello will also have it because func is a reference to sayHello.

Lexical Scoping

Describes how a parser resolves variable names when functions are nested. The word “lexical” refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available.

Nested functions have access to variables declared in their outer scope.

init() creates a local variable called name and a function called displayName().
The displayName() function is an inner function that is defined inside init() and is only available within the body of the init() function.

The displayName() function has no local variables of its own.

However, because inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().

However, the same local variables in displayName() will be used if they exist.

Run the code and notice that the alert() statement within the displayName() function successfully displays the value of the name variable, which is declared in its parent function.

Scope is created when you execute a function

When you call a function like init() you create a scope during the execution of that function. Then that scope goes away.

When you call the function a second time, you create a new different scope during the second execution. Then this second goes away as well.

These two scopes that were created in the example above are different. The variable answer here is not shared between them at all.

Every function scope has a lifetime. They get created and they get discarded right away. The only exception to this fact is the global scope, which does not go away as long as the application is running.

Closures are created when you DEFINE a function

When you define a function, a closure gets created.

Unlike scopes, closures are created when you DEFINE a function, NOT when you execute it. Closures don’t go away after you execute that function.

local scope, parent scope, and global scope are all referenced by the closure. NOT COPIED:

Don’t confuse closures with scopes

In the simple example above, we have three functions and they all get defined and immediately invoked, so they all create scopes and closures.

The scope of function one() is its body. Its closure gives us access to both its scope and the global scope.

The scope of function two() is its body. Its closure gives us access to its scope plus the scope of function one()plus the global scope

And similarly, the closure of function three() gives us access to all scopes in the example. This is why we were able to access all variables in function three().

Another Example

If not global variable v…

Since closures have REFERENCE to variables in scope, they have read/write access

This is why we can change global variables everywhere. All closures give us both read/write access to all global variables.

Closures can share scopes

double and square both share scope parent. This means their closure references variables from parent. Specifically, variable a.
Hence, when we call double the first time, double references var a from parent. It does 10 + 10 = 20. Parent’s var a is now 20.

Then, square references var a from parent. a is now 20 from the call to double due to reference usage. square does 20 * 20 = 400.
Parent’s a is now 400.

We execute double again. double’s closure references a from parent which is 400. It does 400 + 400 = 800. Parent’s var a is now 800.

Another example


output:
3
2

Things can get weird though – People Example

Here we pass an array of objects into a function. We are expecting this function to update property id of our objects.

We use a loop to assign index to the array element’s id property.
The anonymous function created here is stored in heap memory, as well as the var i.

After we run this, the result id are all the same, 103.

Since var i, and all three anon functions are stored in heap memory, when we try to access the ids later in the future, the var i is already 103.
Thus, when you invoke those functions in the future, they will be access i that is 103.

Solution

We need to make sure we store the correct i somehow, and not an i that has already ran through its course to the end.

We do this through two ways:

  • Invoking the function and storing the value right away
  • IIFE
  • “let”
Invoke the function, and storing the value

This is about invoking the function right away, and then assigning the value to people[i][“id”].
As you can see when you call creator(gang), the logs ‘Calculating for index:…’ gets called right away.
Because at each index, the anonymous function gets invoked and then the value is stored.

Thus, whenever you access updatedGang[0].id, you’re simply retrieving the stored value

In this solution, we’re invoking the function RIGHT AWAY, thus creating the scope, and the i is accessed. It will return 0. 0 + 100 = 100. It will then assign the integer 100 to updatedGang[0].id
When i becomes 1, the function executes RIGHT AWAY, creating the scope, and the i is accessed as 1. 1 + 100 = 101. 101 gets assigned to updatedGang[1].id.

… and so on.

using IIFE

As you can see, we now have reference to a function that you can execute in the future. In addition, we also have our own variable ‘index’ to store the i.

The IIFE for index 0 puts the i in its own memory, and stores it.
The IIFE for index 1 puts the i in its own memory, and stores it
…etc

Thus, we can invoke on the fly and still get the correct answer. It is vastly different than our previous example, which is invoke right away, and storing the result.

In other words:

Using IIFE, we first create a function expression and invoke it immediately with a parameter. This creates a context that gets pushed onto our stack context.

Creation Phase:
– We point this reference to global object.
– We create outer reference to scope
– puts parameter ‘index’ in memory
– put anon function j in memory.

Execution Phase:
– We use scope to access people and i. We assign them to anon function which is in memory. This anon function will access parameter ‘index’, which is also stored in memory.

Then this IIFE gets popped from the context stack.
When this loop is done, creator context is popped from the stack.

In the future, when you try to access updatedGang[1].id(), you execute this anon function that is stored in memory. It has index as 1, which is also stored in memory.
Hence that is the reason why we’re able to get the correct value at a later time. We store everything in memory via function definitions and variables.

Using let (block scoped)

We need to use let to make sure we get correct scoping.

A variable declared by let or const has a so-called temporal dead zone (TDZ): When entering its scope, it can’t be accessed (got or set) until execution reaches the declaration.

i in the inner function is not referencing some global var i. It it referencing a block scope variable i, which has been pushed onto the local stack.

it works because, for (let i = 0; i < arr.length ;i ++) defines i as var i for the local block.

in addition:

ref – http://chineseruleof8.com/code/index.php/2017/10/01/let-vs-var-js/

i is only visible in here (and in the for() parentheses)
and there is a SEPARATE i var for each iteration of the loop

like this:

does this:

Hence when we call people[0].id(), we evaluate i, which accesses its local var i as 0. 0 + 100 = 100.
people[1].id(), we evaluate the i, which accesses its local var i as 1. 1 + 100 = 101.
… so on.

Another example

Block Property use copy or strong

ref –
http://stackoverflow.com/questions/27152580/cocoa-blocks-as-strong-pointers-vs-copy

Short Answer

The answer is it is historical, you are completely correct that in current ARC code there is no need to use copy and a strong property is fine. The same goes for instance, local and global variables.

Long Answer

Unlike other objects a block may be stored on the stack, this is an implementation optimisation and as such should, like other compiler optimisations, not have direct impact on the written code. This optimisation benefits a common case where a block is created, passed as a method/function argument, used by that function, and then discarded – the block can be quickly allocated on the stack and then disposed of without the heap (dynamic memory pool) being involved.

Compare this to local variables, which
(a) created on the stack
(b) are automatically destroyed when the owning function/method returns and
(c) can be passed-by-address to methods/functions called by the owning function.

The address of a local variable cannot be stored and used after its owning function/method has return – the variable no longer exists.

However objects are expected to outlast their creating function/method. So unlike local variables, objects are allocated on the heap and are not automatically destroyed based on their creating function/method returning but rather based on whether they are still needed (used) – and “need” here is determined automatically by ARC these days.

So what about Blocks?

Creating a block on the stack may optimise a common case but it also causes a problem – if the block needs to outlast its creator, as objects often do, then it must be moved to the heap before its creating method’s local stack is destroyed.

When the block implementation was first released the optimisation of storing blocks on the stack was made visible to programmers as the compiler at that time was unable to automatically handle moving the block to the heap when needed – programmers had to use a function block_copy() to do it themselves.

While this approach might not be out-of-place in the low-level C world (and blocks are C construct), having high-level Objective-C programmers manually manage a compiler optimisation is really not good. As Apple released newer versions of the compiler improvements where made. Early on it programmers were told they could replace block_copy(block) with [block copy], fitting in with normal Objective-C objects. Then the compiler started to automatically copy blocks off stack as needed, but this was not always officially documented.

There has been no need to manually copy blocks off the stack for a while, though Apple cannot shrug off its origins and refers to doing so as “best practice” – which is certainly debatable. In the latest version, Sept 2014, of Apple’s Working with Blocks, they stated that block-valued properties should use copy, but then immediately come clean (emphasis added):

Note: You should specify copy as the property attribute, because a block needs to be copied to keep track of its captured state outside of the original scope. This isn’t something you need to worry about when using Automatic Reference Counting, as it will happen automatically, but it’s best practice for the property attribute to show the resultant behavior.
There is no need to “show the resultant behavior” – storing the block on the stack in the first place is an optimisation and should be transparent to the code – just like other compiler optimisations the code should gain the performance benefit without the programmer’s involvement.

So as long as you use ARC and the current Clang compilers you can treat blocks like other objects, and as blocks are immutable that means you don’t need to copy them. Trust Apple, even if they appear to be nostalgic for the “good old days when we did things by hand” and encourage you to leave historical reminders in your code, copy is not needed.

Copying and placing folders

http://askubuntu.com/questions/86822/how-can-i-copy-the-contents-of-a-folder-to-another-folder-in-a-different-directo

For local paths:

For full paths:

Objc/c++: Can local variable be accessed outside of its scope

http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope

If you push a local variable onto the stack, and return its address. Then in the parent scope, you have a pointer point to the return address.

After the function completes, you dereference the pointer. The result is unstable. …and really depends on whether the system decides to leave your space alone, or have someone else overwrite it.

You rent a hotel room.
You point your pointer to the return address of the local variable

You put a book in the top drawer of the bedside table and go to sleep.
In your local variable, you do stuff with it

You check out the next morning. your function finishes running
… but “forget” to give back your key. You steal the key! You do not point your pointer to NULL

A week later, you return to the hotel, do not check in, sneak into your old room with your stolen key, and look in the drawer. Your book is still there. Astonishing!

Later in your program, you decide to dereference your pointer. Depending on the circumstances, if the system has not over-written the space for that local variable, then you still see your value there! If the system have over-written it, then you will access something that is bizarre and your program may crash.

How can that be? Aren’t the contents of a hotel room drawer inaccessible if you haven’t rented the room?

Well, obviously that scenario can happen in the real world no problem. There is no mysterious force that causes your book to disappear when you are no longer authorized to be in the room. Nor is there a mysterious force that prevents you from entering a room with a stolen key.

The hotel management is not required to remove your book. You didn’t make a contract with them that said that if you leave stuff behind, they’ll shred it for you. If you illegally re-enter your room with a stolen key to get it back, the hotel security staff is not required to catch you sneaking in. You didn’t make a contract with them that said “if I try to sneak back into my room later, you are required to stop me.” Rather, you signed a contract with them that said “I promise not to sneak back into my room later”, a contract which you broke.

In this situation anything can happen. The book can be there — you got lucky. Someone else’s book can be there and yours could be in the hotel’s furnace. Someone could be there right when you come in, tearing your book to pieces. The hotel could have removed the table and book entirely and replaced it with a wardrobe. The entire hotel could be just about to be torn down and replaced with a football stadium, and you are going to die in an explosion while you are sneaking around.

You don’t know what is going to happen; when you checked out of the hotel and stole a key to illegally use later, you gave up the right to live in a predictable, safe world because you chose to break the rules of the system.

Mark and Sweep algorithm for GC

http://www.cnblogs.com/tekkaman/archive/2012/07/05/2578131.html
http://stackoverflow.com/questions/24799297/circular-reference-memory-leak/24963376#24963376

This algorithm reduces the definition of “an object is not needed anymore” to “an object is unreachable”.

  This algorithm assumes the knowledge of a set of objects called roots Periodically, the garbage-collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.

  This algorithm is better than the previous one since “an object has zero reference” leads to this object being unreachable. The opposite is not true as we have seen with cycles.

  As of 2012, all modern browsers ship a mark-and-sweep garbage-collector. All improvements made in the field of JavaScript garbage collection (generational/incremental/concurrent/parallel garbage collection) over the last few years are implementation improvements of this algorithm, but not improvements over the garbage collection algorithm itself nor its reduction of the definition of when “an object is not needed anymore”.

Cycles are not a problem anymore

In the first above example, after the function call returns, the 2 objects are not referenced anymore by something reachable from the global object. Consequently, they will be found unreachable by the garbage collector.

The same thing goes with the second example. Once the div and its handler are made unreachable from the roots, they can both be garbage-collected despite referencing each other.

Limitation: objects need to be made explicitly unreachable

Although this is marked as a limitation, it is one that is rarely reached in practice which is why no one usually cares that much about garbage collection.

Javascript GC

Currently, Javascript V8’s garbage collection algorithm adopts the mark and sweep algorithm.
Hence, you do not have to worry about circular references.

Modern JavaScript implementations perform garbage collection through a “mark and sweep” algorithm. First they scan through your web app’s entire memory structure starting from the global object, and mark everything they find. Then they sweep through every object stored in memory and garbage collect anything that wasn’t marked. As long as there isn’t a reference to your object from the global object or any stored function, it can be garbage collected.

In Apple’s xCode, the obj-c garbage collector does not. Hence you DO NEED to worry and eliminate any code that has a circular reference, which includes parent/child, blocks, and delegates.

Handoff from  Watch to iOS app

download source

On the Watch side, in a button click responder, we call updateUserActivity method, which is a way to hand off data that the user is currently working on. This method is part of WKInterfaceController.h.

InterfaceController.m

Notice the string key com.rtsao.handoff.

You need to go to your project folder’s Info.plist, add NSUserActivityTypes as an Array, then in that array, add com.rtsao.handoff

handoff-info-1

Then in your Watch Extension folder’s Info.plist, do the same thing.

hand-off-info2

iOS app

AppDelegate.m

Run the program. Also, click the power button on your iphone to lock it.

When your  watch turns on, click on the button to activate the handoff. It calls the updateUserActivity method, which means its ready to pass off the current User’s activities to the paired iOS app.

Now click on the home button of your iphone. You’ll see that your iphone is on the “unlock screen”. You will also see that your app icon appears on the lower left hand side. This means that once the  watch passes off the user’s activity to the iOS app, you can activate the continuation of that user’s activity by sliding this icon up.

handoff-appicon

Once you slide up, your iOS app will appear, and the thread of execution will continue in AppDelegate.m’s continueUserActivity. The continueUserActivity method is part of UIApplication delegate protocol methods.

Look at the parameter userActivity. That contains all of the data you need to start processing the user’s activities. Use the activityType to retrieve the id, and the userInfo to get the data, among other data.

Also notice the restorationHandler block. This block takes an array of UIViewControllers. It then sends each of these UIViewControllers a restoreUserActivityState: message, passing in the resuming activity’s NSUserActivity object.

The window controllers inherit the restoreUserActivityState: method from NSResponder, and each controller object overrides that method to configure its window, using the information in the activity object’s userInfo dictionary.

Hence since we only have 1 main ViewController, let’s pass that in. In is simply self.window.rootViewController.

Then in our ViewController.m, we implement:

You now have the user’s activity in your particular UIViewController and its view hierarchy. Thus, this let’s you take care of processing the data in whatever part of your app.