All posts by admin

Objective C stack and heap

https://mikeash.com/pyblog/friday-qa-2010-01-15-stack-and-heap-objects-in-objective-c.html

Stack
  • The stack is a region of memory which contains storage for local variables, as well as internal temporary values and housekeeping.
  • On a modern system, there is one stack per thread of execution.
  • When a function is called, a stack frame is pushed onto the stack, and function-local data is stored there.
  • When the function returns, its stack frame is destroyed.
Heap

The heap is, essentially, everything else in memory.

  • Memory can be allocated on the heap at any time, and destroyed at any time.
  • You have to explicitly request for memory to be allocated from the heap, and if you aren’t using garbage collection, explicitly free it as well.
  • This is where you store things that need to outlive the current function call. The heap is what you access when you call malloc and free.

Stack vs Heap Objects

Given that, what’s a stack object, and what’s a heap object?

First, we must understand what an object is in general. In Objective-C (and many other languages), an object is simply a contiguous blob of memory with a particular layout.

The precise location of that memory is less important. As long as you have some memory somewhere with the right contents, it’s a working Objective-C object. In Objective-C, objects are usually created on the heap:

NSObject *obj = [[NSObject alloc] init];

The storage for the obj pointer variable itself is on the stack
but the object it points to is in the heap.
In other words, the obj pointer variable is pushed onto the stack. The NSObject object that it points to, is allocated on the heap

The [NSObject alloc] call allocates a chunk of heap memory, and fills it out to match the layout needed for an NSObject.

Using NS Collection classes with blocks

Since Blocks are objective C objects that gets pushed onto the stack…

A Block is the one instance of an Objective-C object that starts on the stack. While you can happily collect together a bunch of Blocks in one of the Foundation provided collection classes (NSArray, NSDictionary, or NSSet), make sure you copy the Block before you do!

The last thing you want is a stack based object to end up in an autorelease pool….

The reason why Blocks start on the stack is because it is really really fast. Orders of magnitude faster than allocating a chunk of memory for each Block.

other ref-

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

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.

calling method on a nil object

A message sent to a nil object is perfectly acceptable in Objective-C, it’s treated as a no-op. There is no way to flag it as an error because it’s not an error, in fact it can be a very useful feature of the language.

From the docs:

Sending Messages to nil

In Objective-C, it is valid to send a message to nil—it simply has no effect at runtime. There are several patterns in Cocoa that take advantage of this fact. The value returned from a message to nil may also be valid:

If the method returns an object, then a message sent to nil returns 0 (nil), for example:

Person *motherInLaw = [[aPerson spouse] mother];

If aPerson’s spouse is nil, then mother is sent to nil and the method returns nil.

If the method returns any pointer type, any integer scalar of size less than or equal to sizeof(void*), a float, a double, a long double, or a long long, then a message sent to nil returns 0.

If the method returns a struct, as defined by the Mac OS X ABI Function Call Guide to be returned in registers, then a message sent to nil returns 0.0 for every field in the data structure. Other struct data types will not be filled with zeros.

If the method returns anything other than the aforementioned value types the return value of a message sent to nil is undefined.

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.

Committing projects up to Github

ref – http://stackoverflow.com/questions/17291995/push-existing-project-into-github
ref – https://help.github.com/articles/fork-a-repo/

Create the repo

Make sure you have created a repository on Github via
https://github.com/new
Enter a repository name, then check the box where it creates a readme file.
Click ok.

Fork

Then fork it locally, directions below are taken from the url here: https://help.github.com/articles/fork-a-repo/

Directions

On GitHub, navigate to your fork of your repository.
Clone URL buttonIn the right sidebar of your fork’s repository page, click
to copy the clone URL for your fork.

Open Terminal (for Mac users) or the command prompt (for Windows and Linux users).

Type git clone, and then paste the URL you copied in Step 2. It will look like this, with your GitHub username instead of YOUR-USERNAME:

Press Enter. Your local clone will be created and the output from your terminal will be something like this:


Rickys-MacBook-Pro:Desktop rickytsao$ git clone https://github.com/redmacdev1988/face-recognizer.git
Cloning into ‘face-recognizer’…
remote: Counting objects: 3, done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
Checking connectivity… done

Clone a single branch

git clone https://your_name@gitcn.company.com:1234/hehe-haha/hehe-haha.git –branch dev

Clone with username

List branches of the the repository

(double dash next to “heads”)
git ls-remote –heads https://git.yourcompany.com/some_person/project_name.git

Change working branch :

Create the branch on your local machine and switch in this branch :

$ git checkout -b [name_of_your_new_branch]
Change working branch :

$ git checkout [name_of_your_new_branch]
Push the branch on github :

$ git push origin [name_of_your_new_branch]

Uploading Project

Then, you’ll see the project folder on your desktop. Copy your source files into the folder. And to upload it to Github you do:

note – The project url can be found on the repo page on the righthand side bar. It should have a little paste icon next to it. Its the HTTPS clone URL…you should be able to just copy and paste to the terminal window

If the system tell you that origin already exists, keep going with the instructions.

Make sure you are in the directory of the folder that Git created on your computer. Then within the folder (which should have a git file) you go:

Rickys-MacBook-Pro:holistic-element rickytsao$ git push -f origin master

It will then ask you for your username and password:


Username for ‘https://github.com’: redmacdev1988
Password for ‘https://redmacdev1988@github.com’:

result:

Counting objects: 651, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (645/645), done.
Writing objects: 100% (650/650), 130.74 MiB | 1.45 MiB/s, done.
Total 650 (delta 19), reused 0 (delta 0)
To https://github.com/redmacdev1988/holistic-element.git
0ddae45..a74a112 master -> master

If you want to remove files, delete the files in your directory.
Then in the same directory, go:

git commit -a -m “removed fluff”
git push origin master

Pulling (cloning) the project onto your machine

git clone https://git.epam.com/ricky_tsao/badmintoneventsapp.git

src refspec does not match any ERROR

If you try pushing to a certain branch and it gives you a src refspec error, it means you are not on that branch. You need to switch to that branch first, THEN, push to it.


git checkout -b Ricky_Tsao
Switched to a new branch Ricky_Tsao


git commit -a -m “cleaned up stuff”
git push origin Ricky_Tsao

Cloning Single Branch

git clone learned –single-branch option to limit cloning to a single branch;
tags that do not point into the history of the branch are not fetched.

git clone -b branch_name –single-branch (double dash in front of “single”) https://gitcn.epam..com:1234/your_name/project_name.git

Merge current local branch with remote

$ git stash
$ git pull origin release/1.0.1
// fix conflicts
// git add, git commit
$ git stash pop

// git add, git commit, git push

See the list of files that have changes between your local and remote

$ git status
On branch dev
Your branch is up-to-date with ‘origin/dev’.
Changes to be committed:
(use “git reset HEAD …” to unstage)

modified: Src/Project/Website/Code/global/css/product.css
modified: Src/Project/Website/Code/global/standalonesim.html

Stash

$ git stash save “—–”
$ git stash list
$ git stash apply stash@{0}

Delete local branch

$ git branch -d feature/login

Pushing new files onto your branch

$ git add .
$ git reset build/config (or whatever path to folder you want to exclude)
$ git commit -m “Add existing file”
$ git push -f origin Your_Branch

Javascript copy by reference

With a = {}; b = a, you get

quoted from stackoverflow:

No, JS doesn’t have pointers.

Objects are passed around by passing a copy of a reference. The programmer cannot access any C-like “value” representing the address of the object.

Within a function one may change the contents of an passed object via that reference, but you cannot modify the reference that the caller had, because your reference is only a copy:

Pictorial

js_ref_1_2

js_ref_3

js_ref_4_5

pointers (C) vs references (Java)

ref – http://programmers.stackexchange.com/questions/141834/how-is-a-java-reference-different-from-a-c-pointer

References might be implemented by storing the address. Usually Java references will be implemented as pointers, but that’s not required by the specification. They may be using an additional layer of indirection to enable easier garbage collection. But in the end it will (almost always) boil down to (C-style) pointers being involved in the implementation of (Java-style) references.

You can’t do pointer arithmetic with references. The most important difference between a pointer in C and a reference in Java is that you can’t actually get to (and manipulate) the underlying value of a reference in Java. In other words: you can’t do pointer arithmetic.

In C you can add something to a pointer (i.e. the address) or substract something to point to things that are “nearby” or point to places that are at any place.

In Java, a reference points to one thing and that thing only. You can make a variable hold a different reference, but you can’t just ask it to point to “the thing after the original thing”.

References are strongly typed. Another difference is that the type of a reference is much more strictly controlled in Java than the type of a pointer is in C. In C you can have an int* and cast it to a char* and just re-interpret the memory at that location. That re-interpretation doesn’t work in Java: you can only interpret the object at the other end of the reference as something that it already is (i.e. you can cast a Object reference to String reference only if the object pointed to is actually a String).

Those differences make C pointers more powerful, but also more dangerous. Both of those possibilities (pointer arithmetic and re-interpreting the values being pointed to) add flexibility to C and are the source of some of the power of the language. But they are also big sources of problems, because if used incorrectly they can easily break assumptions that your code is built around. And it’s pretty easy to use them incorrectly.

splice

Basic Usage

1st param – what index of the array to start
2nd param – how many elements to remove

in firebug console, we first see what test is. Which gives us the result of the full array. Then we do test.splice(1,2), which means at index 1, we remove 2 elements. This returns us “two” and “three”, meaning we removed “two” and “three.

Then we see the results of test again to ensure that “two” and “three” are removed from the original array.

> test
Array [ “one”, “two”, “three”, “four”, “five”, “six” ]
> test.splice(1,2)
Array [ “two”, “three” ]
> test
Array [ “one”, “four”, “five”, “six” ]

in firebug console, we start at index 2, which would be “ten”.
We remove 2 elements, which would be the “ten”, and “six”. The removed elements are returned.
We then add the word “nine”.

> test
Array [ “one”, “four”, “ten”, “six” ]
> test.splice(2,2,”nine”)
Array [ “ten”, “six” ]
> test
Array [ “one”, “four”, “nine” ]

Using splice in List implmentation

We first make a List class default constructor. we initialize member variables. Then we assign function definitions append, remove, length, insert, clear, and toString.

delete the array of elements. then reassign to empty array.

We loop through all the elements of our dataStore array, and if the elements match, we simply return the index.

We first get the index of where we want to remove the element.
Then when we have the index, we use the index as parameter for the splice index to know where to start. The 1 at the 2nd parameter of the splice, means to remove 1 element at that index.

We insert at given position pos, removing 0 elements, and insert the element to be inserted.