Tuesday, 25 February 2014

iOS Tutorial on Enumeration 

So as we are talking about enumeration in iOS,the first thing comes into mind are Collections such as Arrays , Sets and Dictionaries.Why?? Because we need to enumerate i.e go one by one over the objects contained in the collection objects.For example we have a following array

NSArray *exampleArray = @[@"A",@"B",@"C",@"D"];

For accessing the elements of the array you can follow the standard method of C using For Loops i.e

for (<#initialization#>; <#condition#>; <#increment#>) {
        <#statements#>
    }

But its best practice to follow the following techniques described.

In Cocoa there are there basic techniques of enumeration

1)Fast Enumeration
2)Block Based Enumeration
3)Using an Enumerator.

Fast Enumeration

Fast enumeration is the most preferred way of enumerating the collections.

Why??
  • More efficient.
  • Easy syntax.
  • Doesn't allow to mutate(change) the collection you are trying to enumerate.
  • Perform multiple enumerations concurrently.

How to use it?

Syntax - 

for (<#type *object#> in <#collection#>) {
        <#statements#>
    }

Examples :-

NSArray *exampleArray = @[@"A",@"B",@"C",@"D"];
NSDictionary *exampleDictionary = @{@"Key1"@"A",@"Key2":@"B",@"Key3":@"C"};
    
    for (NSString *element in exampleArray) {
        NSLog(@"Element %@ \n",element);
    }

    for (NSString *key in exampleDictionary) {
        NSLog(@"Element %@ with Key %@",[exampleDictionary objectForKey:key],key);

    }

Output :
Element A 
Element B 
Element C 
Element D 
Element B with Key Key2
Element A with Key Key1
Element C with Key Key3

Arrays and sets enumerate their contents, and dictionaries enumerate their keys. NSIndexSet and NSIndexPath do not support fast enumeration.In case of Array the enumeration of objects occurs in the order in which they are inserted.

Block Based Enumeration

The collection objects allow to enumerate their objects using blocks(If you don't know them then you can read about them I would be posting a tutorial for them soon).So how to do it.Stay with me and you will get everything its easy.

How to use it?

Syntax For Dictionary:-

[exampleDictionary enumerateKeysAndObjectsUsingBlock:<#^(id key, id obj, BOOL *stop)block#>];

Example :-

[exampleDictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key,NSString *element,BOOL *stop){
     NSLog(@"Element %@ with Key %@",[exampleDictionary objectForKey:key],key);
        if ([key isEqualToString:@"Key2"]) {
            *stop = YES;
        }
    
    }];


Syntax For Array:-

[exampleArray enumerateObjectsUsingBlock:<#^(id obj, NSUInteger idx, BOOL *stop)block#>];

Example :-

[exampleArray enumerateObjectsUsingBlock:^(NSString *element,NSUInteger index,BOOL *stop){
        
        NSLog(@"Element %@ Index %d ",element,index);
        if (index == 2) {
            *stop = YES;
        }
    }];


The example is quite self explanatory but then also if you didn't got it I would explain one example. 

exampleDictionary is the dictionary we created earlier in the tutorial.

enumerateKeysAndObjectsUsingBlock is the instance method called upon the exampleDictionary and which takes a block with parameters  (id key, id obj, BOOL *stop).

(id key, id obj, BOOL *stop) 

id is used to represent the generic type  and BOOL *stop parameter is used to check whether to stop enumerating or not i.e when the *stop is equal to YES the enumeration of collection will be stopped.




The block-based enumeration methods for the other collections are slightly different in name and in block signature. See the respective class references for the method definitions.

WHY would i need to stop the enumeration ??
 To increase the performance.You should stop enumerating the collection as soon as you find your object or complete your task.

if you have any doubts comment them i would be happy to clear your doubts.Stay tunned :)

Sunday, 16 February 2014

iOS BLOCK BASED API's - UNIT TESTING

UNIT TESTING?

First of all just for the definition sake we can define unit testing as a method used to check the validity and consistency of individual units of your source code


WHAT DO YOU MEAN BY UNITS?

Units can be defined as sets of modules of your computer program.Intuitively a unit can be defined as the smallest part of the application which can be tested.But it is not necessary it would be the smallest part of the application.In procedural programming it can be entire module,but commonly we test individual functions whereas in object oriented programming units are often an entire interface,but could be individual methods.


WHY SHOULD I USE IT?

Unit Tests are very useful for those large projects where you might loose sight of everything that’s going on and while you are adding new code to add feature Y you might be silently breaking feature X without even suspecting.



SO WHAT ARE WE GOING TO LEARN TODAY?

Are we going to learn the complete unit testing?? No, i am going to discuss only about  unit testing block based API's. If you are not familiar with the blocks i would recommend you to go through the Blocks Programming Topics of Apple.If you have worked with the blocks one of the problems you might have faced is unit testing them.

HOW DO WE UNIT TEST THOSE BLOCKS ?

If you are already using Xcode 5.The unit tests are already part of your project.For example If you keep the name of your project as Dedicate you would be saying something like following in your project.











So lets start with what we are trying to learn.Write a test case .Don't just copy paste the code.My assumption is you would be having a block based code similar to the following.












So run the test case and you would never get into the block where we print the log "I am inside the block".What the hell why i am not getting inside that code?. The reason is that the test case doesn't wait for the completion of your block.As a consequence you would be not able to test the block code in any condition.

So Whats the solution?

Have  you heard the term semaphore?If you have then you might begin to think in the direction i am taking you too.But Hey wait I just googled the definition of Semaphore,and the wiki says :

In computer science, particularly in operating systems, semaphore is a variable or abstract data type that is used for controlling access, by multiple processes, to a common resource in a parallel programming or a multi user environment.

We are not  talking about the multiple processes here,but just focus on the highlighted definition . Oh yeah baby, now it  is making some sense.But there is still a question how to implement it.
Implement a new class name Semaphore or whatever you like to keep it.
Add the following lines in Semaphore.h file or xyz.h file whatever you have the kept the name of the class.Add the following lines.














Open the implementation file that is .m file and write the following code.

@implementation Semaphor

@synthesize flags;

+(Semaphor *)sharedInstance
{   
    static Semaphor *sharedInstance = nil;
    static dispatch_once_t once;
    
    dispatch_once(&once, ^{
        sharedInstance = [Semaphor alloc];
        sharedInstance = [sharedInstance init];
    });
    
    return sharedInstance;
}

-(id)init
{
    self = [super init];
    if (self != nil) {
        self.flags = [NSMutableDictionary dictionaryWithCapacity:10];
    }
    return self;
}

-(void)dealloc
{
    self.flags = nil;
}

-(BOOL)isLifted:(NSString*)key
{
    return [self.flags objectForKey:key]!=nil;
}

-(void)lift:(NSString*)key
{
    [self.flags setObject:@"YES" forKey: key];
}

-(void)waitForKey:(NSString*)key
{
    BOOL keepRunning = YES;
    while (keepRunning && [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:1.0]]) {
        keepRunning = ![[Semaphor sharedInstance] isLifted: key];
    }

}

@end


 Just add the following lines in your block code.







Run the test case and Voila you would be able to go inside your block code.Stay connected for more interesting posts of iOS.:) 

Friday, 11 May 2012

Session maintenance using cookies.

Session maintenance using cookies.

In this post i am going to explain how to retrieve and save cookies from the HTTP Post request and send it further with HTTP Get requests.

Retrieving and storing cookies:

Suppose you have a login web service and after successfully authenticating the server provides you with a cookie then following snippet can be used to retrieve and store the cookies.

DefaultHttpClient httpclient = new DefaultHttpClient();HttpPost httppost = new HttpPost(URL);httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  nameValuePairs.add(new BasicNameValuePair("username", YOUR_USERNAME));nameValuePairs.add(new BasicNameValuePair("password",YOUR_PASSWORD);httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));  HttpResponse httpResponse = null;httpResponse = httpclient.execute(httppost);
           List<Cookie> cookies = httpclient.getCookieStore().getCookies(); //  Storing cookies
cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None");//No cookie found } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); // Cookie found 
} }

Now you have retrieved cookies and stored them in the Array List.
Cookie has various parts as follows:
1.Session ID.
2.Cookie name.
3.Domain etc...

Save the required fields from in preferences of cookie store so that you can resend these cookies to get requests to make other services call.

Sending cookies to make other web services calls:

Now you can send these cookies along with the get requests to make other web services calls.
Following snippet shows how to do it.

HttpClient httpclient = new DefaultHttpClient();HttpGet httpget = new HttpGet(url);HttpResponse response;COOKIE_VALUE=PreferenceConnector.readString(activity, PreferenceConnector.COOKIE_SESSION_ID, null); //I had stored the cookies in Prefrences and was retrieving the cookie session ID from there. 
httpget.setHeader("Cookie",  "JSESSIONID="+COOKIE_VALUE); //Here i am sending the Cookie session ID try { response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); RESULT_FINAL = convertStreamToString(instream); instream.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }


Cheers...... 

Sunday, 4 December 2011

Android Saved Instance State Bundle

Hi,
Normally when the device is tilted(i.e. screen orientation is changed) the activity is restarted.Whole activity is destroyed and recreated.So when activity is destroyed ,we need to save the state of activity.This can be done using the onSaveInstanceState and onRestoreInstanceState.


public class SavedInstanceActivity extends Activity {
TextView main_text;
Button update_button;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        main_text=(TextView)findViewById(R.id.main_text);
        update_button=(Button)findViewById(R.id.press_saved);
        update_button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
main_text.setText("SAVED INSTANCE STATE");
}
});
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("SAVED", main_text.getText().toString());
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    main_text.setText(savedInstanceState.getString("SAVED"));
    }
}

Like as you see in the above example if we had not used the onSavedInstanceState() then whole activty would have been recreated and textview would have been blank again.

Click to download the full source code: SOURCE CODE

Thursday, 24 November 2011

Steve Wozniak(Apple Co-Founder) with his Galaxy Nexus and a ice cream sandwich T-shirt to go with it.

Heck of a Strange thing happened in Google's campus in Mount View when Steve Wozniak the co founder of apple became the first person in US to get the Samsung Galaxy Nexus.

This all happened when "Woz" tweeted that he was looking for the Samsung galaxy nexus ,but unfortunately it was not available in US.So "Woz" was invited by the Google's campus in mount view  where he was presented the Brand new Samsung galaxy Nexus and a ice cream sandwich T-shirt.

gsmarena 001 Steve Wozniak gets a Galaxy Nexus from Google, and an Ice Cream Sandwich T Shirt to go with it




;-)....

SOURCE

Wednesday, 2 November 2011

Android Views Animation Tutorial




In this section i will try to explain the 4 types of animation on views which can overall change the impression of the views.

The attached program demonstrates the available types of animations which are:
Alpha - Causes a fading in or fading out effect.
Scale - The view's size smoothly changes.
Rotate - The view rotates.
Translate - The view moves to a different position.


You can individually use these animations or you can also combine these animations into one. Combining of animations is done with help of animation set.First i will explain how to use these animations individually.

ALPHA ANIMATION: Alpha animation is used in fading in and fading out of views. 

<alpha 
android:fromAlpha="0.0" 
android:toAlpha="0.9"
android:duration="3000" />

SCALE ANIMATION: Scale animation is used for changing the size of view.


<scale 
android:fromXScale="1.0" 
android:fromYScale="1.0"
android:toXScale="2.0" 
android:toYScale="2.0" 
android:duration="3000" />

ROTATE ANIMATION: Rotate animation is used for rotating a view around a particular axis.


<rotate 
android:fromDegrees="359" 
android:toDegrees="0"
android:duration="3000" 
android:pivotX="50%" 
android:pivotY="50%" />

TRANSLATE ANIMATION: Translate animation is used to change the position of a particular view.

<translate 
android:fromXDelta="300%" 
android:toXDelta="0%" 
android:fromYDelta="0%"
android:toYDelta="0%" 
android:duration="3000" 
android:zAdjustment="bottom" />

You need to keep these XML files in anim folder in res folder.
And finally to use this application in your Activity you need to use the following piece of code:




final Animation anim=AnimationUtils.loadAnimation(getApplicationContext(), R.anim.animation);// where animation is the name of the anim file which contains any of the above mentioned animation.




Download free source code here.

Tuesday, 1 November 2011

(Nokia choosing WP7 over Android)

                 As my title says i am going to talk about the thing which is in every one's mind i.e. why Nokia chose WP7 over Android although knowing the success of Android in the mobile market.So i m going to compare some of the features of Android and WP7.

                 During the Q&A during Nokia's Capital Market Day, Elop said that Android did not allow them to differentiate enough. This seems weird, since Android is considerably more open and free than Windows Phone 7. However, I think what he meant is that Nokia would not have a say in the actual development direction of Android. And this is where Microsoft comes in.

Nokia knew that it was too late to join the Android party—Android had become a crowded space. Creating a standout Android phone would not only be difficult given the experience of other companies but because it could get lost in the maul of Android phones available. Even Android phone makers would admit that it's hard to stay at the top of the Android power rankings—hell, doesn't it seem like the "best Android phone" only has a lifespan of a month before it gets dethroned? Nokia saw Google eventually getting all the profits as hardware gets commoditized.

And maybe Windows Phone 7 will have those same hardware "issues" as Android but Nokia felt it could differentiate its handsets by dropping in Nokia specific features like their Navteq location-based services. That, they felt, would give them a leg up.

But none of those arguments seem to matter as much as this one: Nokia didn't want to lose the smartphone wars without giving Google and Apple an honest fight. Choosing Android would mean that they'd become a bit player in a two-horse race (Apple vs Google). Choosing Windows Phone means they're hoping and fighting to add another horse. It might be too late and maybe Nokia had to sell their soul, who knows, but I respect any one who goes down swinging.