Thursday, December 26, 2013

Creating Adobe - AIR Native Extension for iOS

Holla Amigos !,

In todays blog session I'm going to discuss the  procedure to generate Adobe AIR ANE (Adobe AIR native extension) for iOS devices. Before going further let me first tell you something about AIR and ANE.


What is Adobe AIR?
    The Adobe® AIR® runtime enables developers to package the same code into native apps for iPhone, iPad, Kindle Fire, Nook Tablet, and other Android™ devices, reaching the mobile app stores for over 500 million devices.

What is a native extension?

      Native Extensions for Adobe AIR are code libraries that contain native code wrapped with an ActionScript API. Native extensions provide easy access to device-specific libraries and features that are not available in the built-in ActionScript classes. Examples of native extensions include making a mobile device vibrate, integrating ad-networks and in-app purchasing systems into your games, and using the iOS GameCenter in your iOS games.



This blog also explains one of the most important feature called Method Swizzling and its usage. This was posted by me long back in a Facebook forum.  (https://www.facebook.com/groups/330366610363679/481424851924520)


Now let us start with a demo ANE creation example. We will be creating an ANE to open my blog in iPhone and to show a welcome alert when the application will resign active . We will her do method swizzling for  Application delegate method applicationWillResignActive: .

Here are the steps:

1) Open Xcode and create a new  project to make a cocoa static library. Name it  BlogViewerLib.

2) Add FlashRuntimeExtensions.h from /Applications/Adobe Flash Builder 4.6/sdks/4.6.0/include

3) Modify your BlogViewerLib-Prefix.pch as follows:












Here we imported necessary headers. objc package classes are required for method swizzling.


3) Modify your BlogViewerLib.h as follows:



4) Modify your BlogViewerLib.m as follows:











Lots of coding!!!!! lets see what we have done in BlogViewerLib class. The class inherits the NSObject class and implements UIApplicationDelegate and UIAlertViewDelegate protocol. UIApplicationDelegate is to implement the application delegate method applicationWillResignActive: .

I didn't used UIAlertViewDelegate methods but if you want you can implement its method. So its optional for this project.

I used a macro definition of a method named DEFINE_ANE_FUNCTION which returns an FREObject (please visit this link.1) and takes following parameters:


FREContext ctx   : please visit this link.2
void* funcData  :
uint32_t argc 
 FREObject argv[] 

please visit this link.3

Then we have defined a blank implementation of applicationWillResignActive: . Inside the implementation block you can define other delegate method also.  customApplicationWillResignActive is the custom method which will replace the delegate method applicationWillResignActive: . It has FREDispatchStatusEventAsync( ) , which send a callback to AS3.0

Please check the implementation of customApplicationWillResignActive() and BlogViewerContextInitializer() to see how method swizzling is performed.


Next you need to implement the contextInitiallizer , contextFinallizer, extesionInitiallizer and extensionFinallizer methods.

please visit this link.4
please visit this link.5


5) Go to edit scheme and use release. Now Clean the build and build. You will get libBlogViewerLib.a .

6) Now create a flex library project. Include AIR SDK  in the project settings. Check Flash builder project in Blogger_AS3 and a project in default folder. Both are the projects with same name . But the one in default has blank implementation.

I this project we have created an extension with id "com.dreams.dreamsbloggerane" . we will use this extension to call method implemented in our objective-C library. Be careful, with the method name. It should be same as the name declared for each FREFunction() in contextInitializer().

The class BlogViewerExtension extends the EventDispatcher, and implements the onStatus() method, which handles the events dispatched from library  by FREDispatchStatusEventAsync().




























7) Check your extension.xml file in ANE_GENERATOR. 



















It defines properties for default and iPhone-ARM platform.

8 ) Building both projects you will get Blogger_AS3.swc files . If you unzip this you will get library file. Get these two library files and keep in iOS and default folders in ANE_GENERATOR. Copy pate the  libBlogViewerLib.a file in iOS folder. SWC file builded for iPhone-ARM must be kept in ANE_GENERATOR. Now cd to ANE_GENERATOR and run following cmd.

admins-MacBook-Pro:ANE_GENERATOR prashantp$ /Applications/Adobe\ Flash\ Builder\ 4.6/sdks/4.6.0_3.9/bin/adt -package -target ane BlogViewerLib.ane extension.xml -swc Blogger_AS3.swc -platform iPhone-ARM -C ios . -platform default -C default .

please visit this link.6



9) You will get .ane file in ANE_GENERATOR . You can now use this as a native lib in your AS3.0 AIR-iOS project. Please check testBlogger project.




source download : download








Monday, December 9, 2013

Mind Re-Fresher Queston

Hola Amigos,

Here is a mind refreshing question for you all. You remember increment (++) operator. Of-course you do .....

Then tell me the difference between y++ and ((y+=1)-1) ?


Ans: Both are same statements

if y = 1

and a = y++ => a = 1; y = 2

and if a= ((y+=1)-1) =>   y+=1 = 2  
=>   ((2) -1) => a = 1; y = 2

Saturday, July 13, 2013

Memory management in Objective - C


Bonjour les amis,

 
This post explains the memory management in Objective-C .
Amigos with C++ background can also refer to this post as it will help them to get a basic idea of how the memory is allocated  and should be handled by you. If you have worked or working on any in house frameworks, this post will help you to get some overview of how memory handler module works in your  your framework.

Before going any further I would first like to explain the "
Brique de fooundation" of memory management in C++, Reference counting. Consider two programmers working on two different classes but using same reference of any object xyz. Now who will delete the memory allocated to this object? If programmer1 delete the object and programmer 2 is still using it he will get a crash. Now how the programmers will know when to delete the object and who will delete it ? Now consider the same situation in a large project where many programmers are working on different classes and they all uses many such object's reference in different classes!!!! problemas? Of-course it's a big problem!!! To solve this issue reference counting was engineered.


What is reference counting ?


Definition from wiki : 
In computer science, reference counting is a technique of storing the number of references, pointers, or handles to a resource such as an object, block of memory, disk space or other resource.

In layman language a reference count is an internal count managed by an object, indicating the count that someone has its ownership.

What is ownership:  An owner of an object is the code snippet which states that "it needs that particular object and no one can delete it".

Methods/Messages related to memory management in Objective- C

alloc (also called "new") : This will create a new object and claims an  ownership of it.

      alloc will explicitly creates an instance of an object. The piece of code creating object using alloc is the only whole soul owner of that object and should delete that object when it has done with it. This will increase the retain count of that object by one. 


retain : This will claim an ownership of an existing object      retain will increase the retain count (reference count) by 1 and makes the calling piece of code a new owner of that object. So some one using retain can say I am also the owner so no one should delete the object till I am done with it . Here also the object should be deleted once its usage is over.


copy : Creates a copy of an object and claims an ownership of it 

    copy will create a copy of the existing object and makes the calling piece of code the owner of that copy of object. So this copy will manage the separate track of retain count. And this copy of object should be deleted when its usage is done.

release : This will delete the object and take away the ownership.

    release will will delete the object decreasing its reference count by 1. But remember "only owner should use it".
 
autorelease :
This will delete the object automatically and don't give the ownership.
    with autorelease  you don't lock the object but you be the temporary owner of the object such that it is deleted automatically when after sometime its usage is over. All the objects are kept in a memory pool called autorelease pool ( an instance of NSAutorelease class) and are deleted at once like  a garbage collector when the pool cleaned. The reference count is made 0 when the objects are deleted.
 
   ARC ("automatic reference counting") is the  the garbage collector mechanism in Objective - C  . All new projects generally uses ARC to prevent the overhead of manual memory management.



Thursday, July 4, 2013

Shallow and Deep Copy in C++

!Hola,

Hope!  my last post was useful for you guys. Guess now you are  aware of dynamic memory allocation for an Array !!!  This post explains the Shallow and Deep copy. Another confusing topic of object oriented programming.

Before proceeding please make sure that you know what is constructor. ( Great!!!!,  that is the minimum qualification required to understand this post)

Now what is a copy constructor ?
A copy constructor is used to copy an object. Suppose we have a class named Dreams. Then the syntax for declaring the copy constructor will be:

syntax:

public Dreams (Dreams & otherDreams);



Make sense!!! 
So what are we doing above ? We are passing the address of the Dream's object to the constructor.
Note : In C++ even if you don't create any constructor, the compiler by default adds a default constructor (interview question)
The default copy constructor provided by the C++ compiler always does the shallow copy. But what actually is a shallow copy? For this let us look into a code snippet below:

class Dreams

{
    public:
    int dreamSize;
     String * dreamCategory;

    
     // empty constructor
     Dreams( )

     {
             dreamSize = 10;
             dreamCategory = new String[dreamSize];
      }

     // copy constructor
     Dreams(Dreams & otherDreams)

     {
         dreamSize = otherDreams.dreamSize;
         dreamCategory = others. dreamCategory;     // note this usage of " = "
      }
  
      ~ Dreams()
      {
             delete[] (this->dreamCategory);
       }
};

class Test

{
      int main( )
     {
          Dreams dream1; // calls  empty constructor
          dreams1.dreamCategory[ 0 ] = 20 ;

         {
               Dreams dream2(dream1);  // calls copy constructor
               cout <<" value of dream1.dreamCategory[0] : %d", dreams1.dreamCategory[ 0 ];

         }    
       
         //segmentation fault error below

         cout <<" value of dream1.dreamCategory[0] : %d", dreams1.dreamCategory[ 0 ];
         return 0;

   }
};


so what is happening here ?
in main() we first created a object  dream1 then we created object dream2 of class Dreams to which we passed dream1.This will call the copy constructor which in turn assigns the member's value of dream1 to dream2.

Did you noticed something awkward happening above? Will the code run properly ?
Answer is no , it will give segmentation fault error!!!!!

Consider the scope of dream2 ( dream2 is inside curly-braces ) . Once the scope of dream2 ends the destructor will be called and the memory allocated for the dream2.dreamCategory will be deleted so will be deleted for dream1.dreamCategory

Why?

Because in copy constructor 
dreamCategory = others. dreamCategory;  will allocate same memory allocation for  dream1.dreamCategory and dream2.dreamCategory.  THIS TYPE OF COPYING IS CALLED SHALLOW COPY





To prevent this we need to create our own version of copy constructor and allocate memory for dream2.category separately like this.

class Dreams

{
    public:
    int dreamSize;
     String * dreamCategory;

    
     // empty constructor
     Dreams( )

     {
             dreamSize = 10;
             dreamCategory = new String[dreamSize];
      }

     // copy constructor
     Dreams(Dreams & otherDreams)

     {
         dreamSize = otherDreams.dreamSize;
         dreamCategory = new String[dreamSize]; // explicit memory allocation
         for(int i = 0, i < otherDreams.dreamSize; i++)

         {
                 dreamCategory[i] =  otherDreams.dreamSize[i];
         }

        // you can also use std::copy instead of for loop      
      }
  
      ~ Dreams()
      {
             delete[] (this->dreamCategory);
       }
};

class Test

{
      int main( )
     {
          Dreams dream1; // calls  empty constructor
          dreams1.dreamCategory[ 0 ] = 20 ;

         {
               Dreams dream2(dream1);  // calls copy constructor
               cout <<" value of dream1.dreamCategory[0] : %d", dreams1.dreamCategory[ 0 ];

         }    
       
         //no segmentation fault error below

         cout <<" value of dream1.dreamCategory[0] : %d", dreams1.dreamCategory[ 0 ];
         return 0;

   }
};

Here as you see we have explicitly allocated memory for dream2.THIS TYPE OF COPYING IS CALLED DEEP COPY.  So the memory map will look like this:




Hope this post was useful. Please give  your valuable comments or if you have any queries feel free to post.

Wednesday, July 3, 2013

Dynamic Memory Allocation For Arrays in C++

!Hola,

This post describes the way to make dynamic allocation for arrays in C++. Sounds interesting ?
For beginners this might be little bit confusing. So, specially for them let me take an example from JAVA. Can you recall how a 1-D array is created in java?

int x[ ] = new int [3];

make sense ? OK !!! so what is the role of "new" here?

new operator allocates memory for three integer elements of array x. Now if you go to Arrays topic of any JAVA book you will find the way to make dynamic array. Now for instance check the 2D array below.

int x[ ][ ] = new int[4][ ];
x[0] = new int[1];
x[1] = new int[2];
x[2] = new int[3];
x[3] = new int[4];

will allocate memory for this array like this:



Make sense !!!!!

I guess you might have got an idea what does dynamic array means. Cool !!!
Now the question is how you will do this in C++ ?
The solution for this is pointers.

We will make use of pointers to dynamically declare and initialize arrays just like we did above with JAVA. The code snippet below will explain everything.



syntax to dynamically create 2-D array:

Object **array;
array = new Object* [rowsize];

for(int i = 0; i < rowsize; i++)
array[i] = new Object[columnsize];

 

example of 1-D array:

int* x = new int[2];
x[0] = 1;
x[1] = 2;

example of 2-D array: ( check this, its similar to what we did above with JAVA )

    int ** a = new int*[2];
    a[0] = new int[2];
    a[0][0] = 1;
    a[0][1] = 2;
    a[1] = new int[3];
    a[1][0] = 3;
    a[1][1] = 4;
    a[1][2] = 5;
   

example of 3-D array:

    int *** b = new int**[2];
    b[0] = new int*[2];
    b[0][0] = new int[2];
    b[0][1] = new int[2];
    b[0][0][0] = 1;
    b[0][0][1] = 2;
    b[0][1][0] = 3;
    b[0][1][1] = 4;
   
    b[1] = new int*[2];
    b[1][0] = new int[2];
    b[1][1] = new int[2];

    b[1][0][0] = 5;
    b[1][0][1] = 6;
    b[1][1][0] = 7;
    b[1][1][1] = 8;

Hope it was useful !!