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

Use double pointers to control pointers outside of functions

dbl_ptr_1

First we have a variable mainInt which has the value 45 and an address.
By definition, a pointer’s value is an address. And a pointer’s address is just some address.

Hence,

1) intPtr’s value, by definition, MUST be an address. In our case, it is the address of mainInt. 0x7fff5fbff86c
2) intPtr’s address is just some address. 0x7fff5fbff860
2) Dereferencing intPtr means we “get the value associated with the address value of intPtr”. The value is 45.

where

So basically, the function definition dblPtr has a double pointer parameter called paramPtr.

1) First, we look at the function call. Since the parameter is a double int pointer called paramPtr, it needs to point to an address of an int pointer. So we give it the address of intPtr, which is 0x7fff5fbff860.

2) Then, for the function defintion’s parameter, we draw a double pointer called “paramPtr” that will point to the address of intPtr given in the function call in step 1.

3) Thus, going into line 1 of dblPtr, we have everything set up as shown in the image.

dbl_ptr_2

What this means is that we dereference paramPtr, which gives us *paramPtr, which will move intPtr itself because we are using a dereference of it. When do:

we get the intPtr and point it to a newly allocated int variable on the heap. That int variable has the value 6969.

dbl_ptr_3

Hence, after the function call, in our specific case, we’d get:

after function call: *intPtr: 6969
after function call: intPtr: 0x100103ad0
after function call: &intPtr: 0x7fff5fbff860

Note that only intPtr would change from pointing to mainInt, to pointing to heap variable 6969. If there were other pointers pointing to mainInt, they would still be pointing there.

Full Source and Sample Output

SAMPLE OUTPUT:

before function call: address of variable mainInt: 0x7fff5fbff83c
before function call: value of variable mainInt: 45
before function call: *intPtr: 45
before function call: intPtr: 0x7fff5fbff83c
before function call: &intPtr: 0x7fff5fbff830
paramPtr is: 0x7fff5fbff830
&paramPtr is: 0x7fff5fbff688
*paramPtr is: 0x7fff5fbff83c
paramPtr is now: 0x7fff5fbff830
*paramPtr is now: 0x100103ad0
**paramPtr is now: 6969
after function call: value of variable mainInt: 45
after function call: address of variable mainInt: 0x7fff5fbff83c
after function call: *intPtr: 6969
after function call: intPtr: 0x100103ad0
after function call: &intPtr: 0x7fff5fbff830
after function call: *temp: 45
after function call: temp: 0x7fff5fbff83c
after function call: &temp: 0x7fff5fbff828

param dereference

First, we have a variable called aNum. That variable has an address, with an associated value:



We then have:

We have an integer pointer point to the address of our aNum variable.



Then we have a function definition:

We use that function like this:

The function gets pushed onto the main function stack. The function returns void so we do not push any return variables onto the stack. Next, the function has

as its parameter. Hence, that parameter gets pushed onto the stack like so:

param_deref_3

The parameter variable param points to whatever intPtr is pointing to…which is aNum’s address.

In our function definition, param gets dereferenced. This means that it gets the value associated with the address that it is pointing to. In our case its the value of aNum, which is 100. It changes it to 45.

param_deref_4

When the function call ends, the whole function with its parameter list gets popped. All we’re left with is aNum, which value has been changed to 45.
the pointer numPtr which points to the address of aNum, and thus, also will get 45 if we dereference it.
param_deref_5

Sample Output

OUTSIDE: int * intPtr is: 100
OUTSIDE: someNumber is: 100
INSIDE: parameter pointer is DEREFERENCED…getting the original value which is: 100
INSIDE: original value changed to: 45

OUTSIDE: int * intPtr is: 45
OUTSIDE: someNumber is: 45

full source

returning a pointer

Pointer manipulation with a return pointer

Just a simple walk through of how pointers work when we have a function with a pointer parameter and a pointer return variable. Full Source down below.

First in our main, we have a variable called aNum that has value 100. Then we have a pointer variable point to the address of our aNum variable.

It should look like this:

return_ptr_1

We look at numPtr’s dereference, which should be 100.

Anything a pointer dereference, it gets the data value contained by the address that the pointer is pointing to. Thus, since our pointer is pointing to an address that contains the value 100 ( aka aNum ).

numPtr dereference is:100
aNum is now: 100

Also, every variable works like a stack. Every additional variable is pushed onto the top. First In Last Out style.

Now, it gets interesting. We have a function definition for returnFunc:

We see that our function definition has a parameter int pointer that points to an int variable’s address.
This means that when we use this returnFunc function, we must give a parameter. In our case, we must give a parameter that the returnFunc’s integer pointer parameter can point to. When we call our function:

we must provide an integer pointer data for the function definition’s parameter to point to. We give it integer pointer “numPtr”. (Remember, numPtr is pointing to aNum)
This is what it looks like:

return_ptr_3

Notice that in our stack, the return variable is there. This means that our returnFunc returns an int pointer. Now, we see that our param_IntPtr, which points to our outside scope’s numPtr, gets dereferenced. That dereference is currently 100. At this point:

numPtr points to aNum.
aNum is 100.
numPtr’s dereference is 100.
param_IntPtr points to whatever numPtr is pointing to (WHICH IS aNum), thus param_IntPtr’s dereference (which is aNum’s value) is 100.

When param_IntPtr dereferences, it takes hold of the data its pointing to, namely, aNum. It changes that value to 45.

Thus, now,
*param_IntPtr, aNum, and *numPtr are all 45 at this point.

return_ptr_4

Then we have this line:

we have a local integer pointer point to a new variable made in the heap with the values 6680.
Then we return the integer pointer (address of the heap variable).

return_ptr_5

Now when we go to our main function scope, we see this:

So hence, our main function integer pointer numPtr points FROM aNum’s address to the heap variable’s address. When we dereference numPtr, we get 6680. When we display numPtr’s address,
it would be the address of the variable in our heap.

return_ptr_6

Console Output

numPtr dereference is:100
aNum is now: 100

heapVariable address is:0x100103ae0
numPtr address is now:0x100103ae0

numPtr dereference is now:6680
aNum is now: 45

Full Source

performSelectorOnMainThread and detachNewThreadSelector

from MobileAppMastery/Threading/02

Basically detachNewThreadSelector detaches a thread and starts its work process. When you need to update the UI, you do it on the main thread. We use performSelectorOnMainThread to do it. We make our main thread perform a chunk of code.

1) get the big task going with:

2) the big task will be running with a ridiculous for loop. Let’s remember to put everything within an autoreleasepool because we want the garbage collection to do its work right away within this cycle.

3) so we’re running happily and this big task is being finished on a separate thread. But what if we want to update the UI? We do it with the performSelectorOnMainThread method:

Basically we run a chunk of code on the main thread. This chunk of code in our case is getting the progress bar to set a new percentage.
Now, the other thing we have to take care of is WHEN do we do this update? In our case, we just do this every time it hits a thousand.
We keep the counter variable ‘updateUIWhen’ to increment by 1000 everytime we update the UI. That way, it i will run 1000 times more before
it does the next update.

Obviously, this is just an example of updating the UI incrementally. You can use whatever method you’d like.

full source:

Simple detachThread example

From MobileMasteryApp/threading/01

long task that blocks UI

In this example, we use the Activity Indicator to indicate the UI response. As you can see, when we start the loop to run through 40,000.

blockUI

to make it start animating. However, on the emulator, you won’t see it moving because the current main thread will process the loop count. When it finishes, then it stops the animating. However, visually, you won’t see the indicator move at all.

Non blocking task

In this example, we detach a thread to do our long process for us. Thus, this spares the main thread of extra work. The main thread’s task is to update the UI and do little processing as possible. Leave the heavy lifting to separate threads.

Obj-C instance variables and properties (ivar, property)

ref – http://stackoverflow.com/questions/7057934/property-vs-instance-variable
http://stackoverflow.com/questions/9702258/difference-between-properties-and-variables-in-ios-header-file

An instance variable is unique to a class. By default, only the class and subclasses can access it. Therefore, as a fundamental principal of object-oriented programming, instance variables (ivars) are private—they are encapsulated by the class.

By contrast, a property is a public value that may or may not correspond to an instance variable. If you want to make an ivar public, you’d probably make a corresponding property. Declaring (and synthesizing) a property generates getter and setter methods for the instance variable.

But at the same time, instance variables that you wish to keep private should and do not have corresponding properties…so they cannot be accessed from outside of the class.

In Practice

Instance variables declared in .h files are NOT accessible from the outside.

As you can see, pubIVar does not show up and cannot be accessed. Whereas, publicProperty does show up, and we can access it. What we’re accessing in the image is its getter method.

only_property_shows

Of course, instance variables declared in the private extensions of the .m files are obviously also private.

Defining Properties

The approach currently suggested by Apple (in templates) is:

Define property in header file, e.g.:

Then synthesize & declare ivar in implementation:

The last line synthesizes the gameCenter property and asserts that whatever value is assigned to the property will be stored in the __gameCenter ivar. Again, this isn’t necessary, but by defining the ivar next to the synthesizer, you are reducing the locations where you have to type the name of the ivar while still explicitly naming it.

Instance Variables (iVars)

Instance variables, sometimes referred to as

ivars

, are variables declared for a class that exist and hold their value throughout the life of a corresponding class instance (i.e., object). The memory used for instance variables is allocated when an object is first created, and freed when the object is deallocated.

In your interface, you can formally declare an instance variable between the braces, or via @property outside the braces, or both. Either way, they become attributes of the class. The difference is that if you declare @property, then you can implement using @synthesize, which auto-codes your getter/setter for you. The auto-coder setter initializes integers and floats to zero, for example. IF you declare an instance variable, and DO NOT specify a corresponding @property, then you cannot use @synthesize and must write your own getter/setter.

Access to those iVars

@private: The instance variable is only accessible within the class that declares it and other instances of this class type.
@protected: The instance variable is accessible within the class that declares it and the instance methods of any of its subclasses. This is the default scope if a protection level is not specified for an instance variable.
@public: The instance variable is accessible from everywhere.
@package: The instance variable is accessible from any other class instance or function, but outside the package, it is treated as private. This scope can be useful for libraries or framework classes.

Although instance variables provide convenient, direct access to an object’s state, they expose the internals of a class—and this violates the OOP principle of encapsulation. Therefore, instance variables should only be declared when necessary, and the declaration should be in the class implementation, not the public interface.

.m implementation file:

usage for trash:

Also, take note that other classes can’t use ‘helper’ nor ‘trash’ because they are declared in the interface of the implementation file.

.h header file:

If we are to declare the variable in our header file, we can then proceed to go

instObj.trash = 100;

example

We declare a private variable datePickerView. Notice there is no synthesize. We do this because we want to declare our get/set methods. Which means we want explicit get/set definitions.

We want to define an explicit get method.

And we just use it like so. the get method in our example basically make sure there is a newly allocated variable if a previous one is not detected.

ns copying

ref: http://stackoverflow.com/questions/4089238/implementing-nscopying

To implement NSCopying, your object must respond to the -copyWithZone: selector. Here’s how you declare that you conform to it:

Then, in your object’s implementation (your .m file):

What should your code do? First, create a new instance of the object—you can call [[[self class] alloc] init] to get an initialized obejct of the current class, which works well for subclassing. Then, for any instance variables that are a subclass of NSObject that supports copying, you can call [thatObject copyWithZone:zone] for the new object. For primitive types (int, char, BOOL and friends) just set the variables to be equal. So, for your obejct Vendor, it’d look like this:

NSCopying in Base and Sub hierarchy

http://stackoverflow.com/questions/4472904/implementing-nscopying-in-subclass-of-subclass?rq=1
http://stackoverflow.com/questions/18673296/overriding-readonly-property-in-subclass

Base Class

The base is class is straightforward. We only have two member variables, but do not want others to access them. So we declare readonly in @property in the .h file. However, we DO want to modify them in our own implementation. We declare readwrite in our @property in the .m file:

Today.h

Notice the @protected above the member variables. I did this so that children classes can access these member variables.

Today.m

Be sure to synthesize them. Its basically getter/setter = iVar

In our case, since we we did not specify an iVar like this:

dayPerformance_PlacingCount is the iVar
and

makes it run through the setter/getter methods.

So the idea behind copyWithZone is that we need to make a deep copy. Hence everything should have its own address. Staying true to that assertion, we must first dynamically allocate the object to be returned:

We create an empty self class. But wait, What about its member variables? They need to be unique with their own address. So we dynamically create those member variables like so:

Then we have our newly created object’s member variables retain them. the variable copy is our newly created Day variable:

..and then we just return that copy variable.

thus, it gets returned like so:

Thus, yourDay takes on a whole newly allocated Day instance with its own member variables and all.

Base class’s copy method

To use it in your main, you go:

Result:
-[AppDelegate application:didFinishLaunchingWithOptions:] [Line 58] – ~~~~~~~~dayOne~~~~~~~~~~~~~
-[AppDelegate application:didFinishLaunchingWithOptions:] [Line 59] – dayOne’s address: 0x16dc1f80
-[AppDelegate application:didFinishLaunchingWithOptions:] [Line 60] – dayPerformance_PlacingAmount address: 0x16dc1fa0
-[AppDelegate application:didFinishLaunchingWithOptions:] [Line 61] – dayPerformance_PlacingAmount value: 1204.500000
-[AppDelegate application:didFinishLaunchingWithOptions:] [Line 62] – ~~~~~~~~~~~~~~~~~~~~~

-[AppDelegate application:didFinishLaunchingWithOptions:] [Line 66] – ~~~~~~~~dayTwo~~~~~~~~~~~~~
-[AppDelegate application:didFinishLaunchingWithOptions:] [Line 67] – dayTwo’s address: 0x16dc22a0
-[AppDelegate application:didFinishLaunchingWithOptions:] [Line 68] – dayPerformance_PlacingAmount’s address: 0x16dc22e0
-[AppDelegate application:didFinishLaunchingWithOptions:] [Line 69] – dayPerformance_PlacingAmount’s value: 1204.500000
-[AppDelegate application:didFinishLaunchingWithOptions:] [Line 70] – ~~~~~~~~~~~~~~~~~~~~~

As you can see, the Day addresses are different from the copy. As well as the member variables. In this particular case, I only printed out instance variable dayPerformance_PlacingAmount.

Fast Enumeration with Collections

Fast enumeration is an Objective-C’s feature that helps in enumerating through a collection.

Collections in Objective-C

Collections are fundamental constructs. It is used to hold and manage other objects. The whole purpose of a collection is that it provides a common way to store and retrieve objects efficiently.

There are several different types of collections. While they all fulfil the same purpose of being able to hold other objects, they differ mostly in the way objects are retrieved. The most common collections used in Objective-C are:

NSSet

NSArray

NSDictionary

NSMutableSet

NSMutableArray

NSMutableDictionary

Fast enumeration Syntax

for (classType variable in collectionObject )
{
statements
}

Here is an example for fast enumeration.

C++ reference

When you use a reference at the parameter, it gets bound to the outside variable that gets passed in. Namely, in our example, passByRef gets bound to variable. Modifications are made up the same address.

A reference can only be bound ONCE.

Thus, once it gets bound, any modification to that reference takes place outside as well.
So for any assignments inside method test, it happens to variable on the outside as well.

If you try to rebind the reference doing something like:

you’ll get an reassignment error.

	

Objective-c’s Addresses and Pass by References

In CPU, a switch is to describe a bit. A bit represent either 0 or 1. You switch on or off. 1 or 0. Thus, its called a switch.

Eight of these bits make up a byte. Each representation of these bits make up a representation. For example, in a byte, we can have:

00000000 (0)
00000001 (1)
00000010 (2)
00000011 (3)
…etc

So as you can see, if we were to make each representation a number, we can have up to
2^8-1 representations. where 8 is the number of bits.
Currently, the example is binary.

Hexadecimal Numbers is a more complex system than using just binary or decimal and is mainly used when dealing with computers and memory address locations.

By dividing a binary number up into groups of 4 bits, each group or set of 4 digits can now have a possible value of between “0000” (0) and “1111” ( 8+4+2+1 = 15 ) giving a total of 16 different number combinations from 0 to 15. Don’t forget that “0” is also a valid digit.

Thus, a 4 bit binary number is a hex digit. If a system has 32 bits, we can say it has 8 hex digits.

If we were to work with hex, each hex digit would have 16 representations: 0123456789abcdef

In computers, data is represented by an address. An address is a hex representation.

The address of a variable is the location in memory where the value for that variable is stored.
To get the variable’s address, you use the & operator:

Notice the %p token. That’s the token you can replace with a memory address. Build and run
the program. You’ll see something like:

i stores its value at 0xbffff738

its in hex which is calculated like this

Storing Addresses in pointers

Declare a new variable named addressOfI that is a pointer to an int. Assign it the address of
i.

Getting the data at the address

Notice that the asterisk is used two different ways The first is in the declaration where you declare the variable addressOfI to be an int *. That is, it is a pointer to a place where an int can be stored.
The second is where you read the int value that is stored at the address stored in addressOfI. (Pointers are also called references. Thus, using the pointer to read data at the address is sometimes called dereferencing the pointer.)
You can also use the * operator on the left-hand side of an assignment to store data at a particular address:

Passing the Reference…by value

This is known as pass-by-reference. That is, you supply an address (also known as “a reference”), and the function puts the data there.

Changes would take place inside method ONLY if you do not move pointer

If you don’t move the parameter pointer, it would work.

For example:

objc_ref_1

In detail, here’s why its pass by value of the reference:

objc_ref_2

If you run it, you’ll see that the ptr inside the function points away to another fresh allocated integer. The outside did not move.

In order to really use a reference (similar to that of C++) to modify the data passed into a method, you need to use a double ptr:

Using pointer of pointer to make changes permanent from inside the method

Pass by Copy

As you can see, the address of our variable is different outside, than the address of the parameter variable inside test2.

Basically you just copy the value in. The parameter is basically a newly created variable on the stack with a different address, but has the same value as what you pass in.

passbyvalue