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

Import another project/framework (ADAL) into your project

ref – http://www.insert.io/frameworkios8xcode6/

Let’s say we want to get a project called ADAL from the git repository and then add it to our project as an external framework for us to use.

First, let’s get the project:

git submodule add https://github.com/AzureAD/azure-activedirectory-library-for-objc adal
cd adal
git checkout tags/2.1.0

Optionally, later don’t forget to add this framework to your git, and push it.

cd ..
git add adal
git commit -m “Use ADAL git submodule at 2.1.0”
git push

Locate the ADAL project folder

the adal folder will be downloaded into your root git directory. (the one with the .git hidden folder)
You will see the ADAL project. Inside, you’ll see several folders. Locate the main ADAL folder with the source files by looking for a .xcodeproj file, along with src folder and its header/implementation files.

source_files

Drag the project over

Make sure you drag the .xcodeproj file over to your project space. Open it and you’ll see the src folders and what not. Look in the Products folder. You will see the ADAL.framework. That is what we’ll be importing into our project.

drag_project_over

Select your Target, then Build Phases, then click on Link Binary With Libraries

Also, in Target, then Build Phases, then Target Dependencies, make sure you add the ADAL framework as well

target_link_library

Click on the ADAL framework and import it.

select_it

Make sure you’ve imported the framework. The run the project.

framework_should_appear

Inserting some code

Finally, in your ViewControllelr.m, import the header file and you should get no errors.

add some define strings for the table names in our azure cloud

Let’s create a service so the view controller can communicate with the cloud tables

Set up the service with the table name and query

dyld: Library not loaded

http://stackoverflow.com/questions/24993752/os-x-framework-library-not-loaded-image-not-found

After you’d made sure there are no errors, if you run into an image not found error, it just means that in your Target, General, Embedded Binaries, click the ‘+’ button and add the ADAL ios framework from its original directory. (NOT the one you dragged into your project)

add_embedded_binaries

Converting existing Project to read from Azure Backend

Import Data Model

File >> New >> File >> Data Model. Name it “Activities”.

Ctrl + click >> Show in Finder. Then drag that file onto a text editor such as sublime. You will see basic xml file.

Drag and drop an existing data model file onto the text editor. Copy and paste all the content into your Activities file. Save and close. Your data model should be now updated. Your iOS data model is ready.

Basic Core Stack Class

Create a basic core data stack class with a context, MOC, and PSC.
Make sure the your sql file name, and the data model name are specified.

core data demo

#define DATA_MODEL_FILENAME @”Activities”
#define SQL_FILENAME @”Activities.sqlite”

QSTodoService

Azure should generate a QSTodoService object that does all the reading and writing of data for you.

Unfortunately, it also generates core data code that sits in your AppDelegate. Pull all the core data code out onto your own CoreDataStack class so that AppDelegate is clean.

Then, make these modifications to your QSTodoService:

Use your core stack and its context in QSTodoService’s init method. Commented out code is the original.

ViewController

conform to NSFetchedResultsControllerDelegate protocol

specify what/how you want to fetch for the fetchedResultsController

In the viewDidLoad, make sure you create your QSTodoService because we are going to implement a refresh method that uses it to sync all the data between your app the backend service.

use the fetchedResultsController to get the objects

Add data attribute to table and app

Let’s say we want to add an attribute event_date, so that the iOS app takes in that date, and can send and store it in an Easy Table on Azure backend.

Azure backend side

Click on the designated table, you add the column attribute. Save it.

add_column

iOS side

Note: For ever new attribute you add, make sure you delete the old app that’s installed on your device. This is so that the existing app’s Core Data mode does not conflict with your new addition.

After you have finished your Easy Table, you use Quick Start to generate an iOS project that connects its Core Data to the Easy Table in Azure backend.

What you pull from the Easy Table depends on your NSFetchController:

  • entity
  • predicate
  • sortDescriptors

of the NSFetchController get method like so:

So we want to match the event_title attribute we added on the Azure backend.

We do so by manipulating our .xcdatamodelId file. In core data, each entity matches that of a table. Look for the TodoItem (or whatever table name you have created in Azure) entity. Click on it, and click the plus button to add it.

add_attribute_to_entity

In your iOS code, we pass the data dictionary to the Azure backend to fill in on the attribute. Thus, just make sure you put the key for “event_date”, and the value that you want to send, which in our case is NSDate.

Then, run your app. Add an entry. Go to your dashboard, and refresh the table rows. You will see your results there.

column_reflected

@public, @private, @protected (objc)

ref – http://stackoverflow.com/questions/844658/what-does-private-mean-in-objective-c

The @public, @protected, @private are called accessor modifiers. They provide access visibility to the instance variable.

So we declare 3 iVar using @public, @protected, @private.

We then declare a child class, and declare MyFirstClass as a parent class.

The basics are laid out here.

  • @public iVars CAN be accessed by the child class
  • @protected iVars CAN be accessed by the child class
  • @private iVars CANNOT BE accessed by the child class

Since we do not provide any accessor methods via properties, the instance varaibles are not accessed via the dot notation (.)

Rather, they are accessed through the arrow ( -> ).

enforce the use of accessors

Say a developer writes a class, then write properties and accessors. However, what if some other developer goes

xcode 4.x+ automatically puts @private in the template for an object. Thus, you don’t have to worry about other people accessing your instance variable with the arrow and modifying unexpectedly.

The only way to modify the instance variables, is through your property methods.

Private methods in Objective C are semi private

ref – http://blog.akquinet.de/2013/03/28/clean-objective-c-private-methods-in-objective-c/
http://www.friday.com/bbum/2009/09/11/class-extensions-explained/

A word about usage

When implementing a class, it is common to have a set of methods that only appear in the class’s @implementation. Often, they are spread around the @implementation and generally appear just above whatever method first uses the private method (if they were to appear below, the compiler will warn).

Eventually, this becomes unwieldy and the developer will capture the private method’s declarations into a category declaration at the top of the implementation file. Something like:

The resulting problem is that the compiler will not check to make sure you have implemented all of the methods declared in that category. Nor will it catch, say, spelling errors in the method declarations in the implementation.

This is because a category with no corresponding implementation is an informal protocol in Objective-C. It is a set of method declarations that can optionally be implemented, often on a subclass of the class with the category declaration.

Because a class extension effectively extends the class’s primary interface, changing the above declaration to the following makes the declared methods have the same requirements as methods declared in the class’s oft public primary interface.

Background

One common complaint for many new to Objective-C is that the language lacks support for private methods within a class. There are compiler directives for instance variables: @private, @protected (the default) and @public. link

However, if you want to hide methods, there is no specific directives to help.

The Problem

Using private methods, we can generally hide the details or behaviors of a class from other classes. These other classes may be clients, Categories, or subclasses.

Compile-time private methods are supported; if a class doesn’t declare a method in its publicly available interface, then that method might as well not exist as far as your code is concerned.
In other words, you can achieve all of the various combinations of visibility desired at compilation time by organizing your project appropriately.

For example:

To avoid exposing a method as part of a class’s API, we do not declare it within the @interface section but within the @implementation section.

makeActivationSound is current exposed. Let’s say we want to make this private, and not let others access this method. We so by removing it from the interface Lightsaber, and put it either in the “private extension” of the Lightsaber class, or simply just declare it as a method within the implementation file.

Now, a private method like makeActivationSound can no longer be called by another class. A method call from a Jedi class like:

is no longer possible.


Compiler error: Method ‘makeActivationSound’ is defined in class
‘Lightsaber’ and is not visible.

Methods are semi private in Objective C

using performSelector to call private methods

Although if we use the performSelector method or the Objective-C Runtime library, we can still invoke private methods.
switchOn is the public method, which calls the private method makeActivationSound of the LightSaber class.
From ViewController, by using performSelector, we still able to manage the private method.

performSelector_callPrivateMethod

The result would be:

BB-ZSHOOOO
BB-ZSHOOOO

Hence there is no true private methods in Objective C.

Using subclasses to access private method

When child classes access the Lightsaber public method switchOn, it will access Lightsaber private method makeActivationSound.

Extending the base class

So say another developer comes in and want to extend the Lightsaber class into a child class called DoubleBladedLightsaber

The developer wants to over-ride the switchOn behavior, and therefore calls [super switchOn]. Then, he wants to add an additional functionality so he declares his own private method. And calls it right after using the base class’s switchOn.

UH OH! PROBLEM

[[DoubleBladedLightsaber new] switchOn];

What he gets is:

BB-ZSHUUUU
BB-ZSHUUUU

The 1st BB-ZSHUUUU is from [super swithcOn]. The switchOn in the base class then calls makeActivationSound. However, it sees that the child class have over-ridden its makeActivationSound, and thus, uses the child’s makeActivationSound method. This results in the output BB-ZSHUUUU, and not BB-ZSHOOOO.

The 2nd BB-ZSHUUUU is just a call to its own private method makeActivationSound. THEREFORE:

Private methods in Objective-C are not as private as in other modern object-oriented programming languages. They are semi-private and have polymorphic behavior.

In objective C, we can (accidentally) compromise the implementation of our extended class. The probability of unknowingly overriding a private method rises when we extend a framework or library class without having access to its source code.

To reduce the risk of accidental method overriding, we should add a prefix to the names of private methods that is as unique as possible.

For this reason, one should use an uppercase abbreviation of the company and/or the product name. In our example that could be the prefix AQN_LS_ for the company akquinet and the product Lightsaber:

After this modification, the [super switchOn] will access its own class’s private method.

So, the risk of accidentally overriding a private method depends on the uniqueness of its name.

  • As private methods can be overridden in Objective-C, there is a risk of compromising the implementation of an extended class.
  • Therefore, always use an application-specific unique prefix for the names of private methods.
  • A single underscore character (_) may not be used as a prefix, as this is reserved for Cocoa classes.

instance variable strong references?

ref – http://stackoverflow.com/questions/16461343/ivars-references-strong-weak-or-what

Default behavior of instance variable

Instance variable maintains a strong reference to the objects by default

Why don’t we specify weak/strong for iVar like properties?

Local variables and non-property instance variables maintain a strong references to objects by default. There’s no need to specify the strong attribute explicitly, because it is the default.
A variable maintains a strong reference to an object only as long as that variable is in scope, or until it is reassigned to another object or nil.

If you don’t want a variable to maintain a strong reference, you can declare it as __weak, like this:

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.

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.

pointer array parameter passing

Create a new Array on the Heap

Creating a new array on the heap basically means:

1) we create a row of new objects that are next to each other
2) We then have an index pointer pointing to it. A index pointer is a pointer pointing to the FIRST element of the array. That way, we can access the rest of the array. If there is no index pointer, we wouldn’t know how to access the rest of the array elements.

1) We create the row of new objects like so:

2) Then we create the index pointer and point to it like so:

That’s it, and what this looks like in memory is this:

ptr_to_array

The index pointer by default is pointing to the 1st, or 0th element of the array.
The reason why we have an index pointer is so that we can reference the whole array like so:

0th element *(arrayA)
1st element *(arrayA + 1)
2nd element *(arrayA + 2)
nth element *(arrayA + n)

Thus, you can display all the elements in an array via an for loop and simply using the index i to display whatever element you’d like. That is the most important purpose of the index pointer.