Wednesday, November 23, 2011

NSCountedSet (grouping array objects with their total number of counts)

This class gives the count of an object present in an array.

For example: If we have an array named myArray with objects: (AA,HH,TT,SS,AA,KK,TT,TT,XX,HH,HH,HH,SS,SS)

Then to get total no of count of every object only write this code:

 NSCountedSet * set = [[NSCountedSet alloc] initWithArray: myArray];
        for (id obj in set)
            NSLog(@"%d - %@", [set countForObject:obj], obj);

Now you can use this [set countForObject:obj] and obj according to your requirement. 

For example it you want to display this in a table with non-repeated objects and with count you can assign above value in a dictionary like this: 

NSMutableDictionary *dirCount = [[NSMutableDictionary alloc]init];
NSCountedSet * set = [[NSCountedSet alloc] initWithArray:arrForTypeGroup];

        for (id obj in set)
            NSLog(@"%d - %@", [set countForObject:obj], obj);
            [dirCount setObject:[NSNumber numberWithInt:[set countForObject:obj]] forKey:obj];

 NSLog(@"Output: %@", dirCount);

Now use this dictionary to display in table.

Happy Coding :)

Sunday, November 13, 2011


PhoneGap lets developers use web technologies to develop an iPhone app. Apple has a web browser object developers can use to display HTML content. Usually developers use it to display HTML from a remote web server. What PhoneGap does is let developers create their user interface using HTML in the web browser object instead of the built-in user interface objects (buttons, lists, text fields, etc).
Normally, this would be very limiting, since web browsers can't access most of the services a smartphone provides - what PhoneGap does is "bridge the gap" (hence the name) between the smartphone and the web browser by exposing smartphone services using JavaScript.
For developers that don't have experience with a smartphone's native development tools, using PhoneGap lets them leverage their knowledge of HTML and JavaScript to make an app. PhoneGap also makes it easier to support multiple smartphone platforms because much of the HTML and JavaScript can be reused between platforms which have this web browser object. (iPhone, Android, the newest Blackberry phones, and Palm webOS phones).
To clarify further, the HTML and JavaScript you put into a the web browser object in a PhoneGap app isn't served by a web server over the Internet - it is embedded into the app. That doesn't mean your app is forever limited to what is put into it when it ships - just as they would otherwise, the developer integrates the PhoneGap screens with your remote data sources (typically via JSON web services) - in this case the PhoneGap screens are like templates. If changes to the template are needed, the developer updates them and submits an updated app to the App Store. This is no different than for apps that don't use PhoneGap - any changes to apps must be re-submitted to the App Store before they can appear on people's phones.

Saturday, November 12, 2011

Agile Software Development Process

In my new company, we follows Agile process for software development, and it is my first experience with Agile software development process. And it is really awesome process because in this process every thing is pre planned what to deliver when and no worry about whole software delivery :)

What is Agile software development process ?

Agile Process is basically based on iteration. In this process after requirement analysis it is decided that when we will deliver which iteration, and what will deliver in which iteration.

Step by Step Agile Development Process :

  1. Requirement Analysis.
  2. Plan All iteration release date upto the final delivery.
  3. Decide which software feature will be deliver in which iteration.
  4. Before 2 days of 1st iteration final release we release our 1st iteration for QA&Testing.
  5. In these two day we resolve all issues and finally release 1st iteration.
  6. Now we proceed for 2nd iteration.
  7. This time we have to release second iteration with all resolved issue of iteration 1.
  8. The above process is repeated upto the final release of application.

iCloud implementation

Step by step method to implement icloud
Make sure your device is running iOS 5.
Turn on iCloud.
When you turn on a new iOS device or after you’ve completed the update to iOS 5, follow the onscreen instructions to activate your device and set up iCloud.
If you skipped the setup process or want to change your iCloud settings, tap the Settings icon on the Home screen and select iCloud.
Customize your settings.
Tap the Settings icon and select iCloud. Tap the On/Off switches to enable individual iCloud services, including Photo Stream, Documents, Find My iPhone, and more.
To enable Backup, tap Storage & Backup, then switch on iCloud Backup.
Now go to the Provisioning Portal to enable iCloud storage for your iOSapplication. Enabling this feature requires that you have an updated provisioning profile on your development systems. Xcode 4 handles this step for you automatically.
Add a new Entitlements file to your application and use it to configure the iCloud features for your application uses. Set the keys and values like this:

           •Now we have to do Entitlements  settings. Go to your target and select Summary tab and do the settings so           that it will look like this:

           •Now we have to do some setup for bundle settings. For this add a new setting bundle file under
           •Resource option in your project , it will have extension .bundle. Now this file contain a Root.plist file.
           •In Root.plist you will get 2 key, one is Preference Items with 4 items and another is Strings Filename. Delete all the items under Preference Items and setup it like this:

Now come on code, Go to your appDelegate.m file and write these line in didFinishLaunchingWithOptions method :
   [[NSUserDefaults standardUserDefaults] setValue:@"YES"   forKey:@"enableiCloud"];
  NSFileManager *fileManager = [NSFileManager defaultManager];
  NSURL *iCloudURL = [fileManager                   URLForUbiquityContainerIdentifier:@""];
  BOOL check = [fileManager isUbiquitousItemAtURL:iCloudURL];
  NSUbiquitousKeyValueStore *cloudStore = [NSUbiquitousKeyValueStore   defaultStore];
   [cloudStore setString:[iCloudURL absoluteString] forKey:@"iCloudURL"];
   [cloudStore synchronize]; // Important as it stores the values you set before on iCloud

// Get the path og file/document to be send on iCloud from document directory.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0];
 NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"saved.png"];
BOOL existFile = [fileManager fileExistsAtPath:writableDBPath];
// If the file exist then send it on iCloud.
 if (existFile { 
   NSError *errorOut=nil;
     BOOL success =[fileManager setUbiquitous:YES itemAtURL:[NSURL   URLWithString:writableDBPath]   destinationURL:iCloudURL error: &errorOut];
      NSLog(@"Error: %@", errorOut);
// Fire Query to check whether the perticular file is present on iCloud or not.
query = [[NSMetadataQuery alloc] init];
 [query setSearchScopes:[NSArray   arrayWithObjects:NSMetadataQueryUbiquitousDataScope,   NSMetadataQueryUbiquitousDocumentsScope, nil]];
 [query setPredicate:[NSPredicate predicateWithFormat:@"kMDItemFSName LIKE '*.png'"]];
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryHandler:) name:NSMetadataQueryDidFinishGatheringNotification object:query]; 
 [query startQuery];

- (void)queryHandler: (NSNotification *) inNotification{
   NSLog(@"The number of results: %i", (int)[query resultCount])

ARC(Automatic Reference Counting)

Automatic Reference Counting (ARC) does:

1.Memory management, job of the compiler.
2.Never need to type retain or release again and again.
3.Reducing crashes and memory leaks.
4.Releases each object the instant, if it is no longer used.
5.Apps run as fast as ever, with predictable, smooth performance.

Before ARC, we had to manually retain/release/autorelease objects to ensure they would “stick around” for as long as you needed them. Forgetting to send retain to an object, or releasing it too many times would cause your app to leak memory or crash.

In Xcode 4.2, in addition to syntax checking as you type, the new Apple LLVM compiler makes it possible to offload the burden of manual memory management to the compiler, introspecting your code to decide when to release objects. 

Apple’s documentation describes ARC as follows:

“Automatic Reference Counting (ARC) is a compiler-level feature that simplifies the process of managing object lifetimes (memory management) in Cocoa applications.”

Before ARC, we had to write:

NSObject *obj = [[NSObject alloc] init];
// do some stuff
[obj release]; 
Or if we are using autorelease then we had to write:

-(NSObject*) someMethod {
  NSObject *obj = [[[NSObject alloc] init] autorelease];
  return obj; // will be deallocated by autorelease pool   later

But with ARC enabled we have to write only :

NSObject *obj = [[NSObject alloc] init];
// do some stuff 

The ARC pre-compilation step will auto-magically turn it into this:

NSObject *obj = [[NSObject alloc] init];
// do some stuff
[obj release]; // **Added by ARC** 

How Automatic Reference Counting Works

ARC is a pre-compilation step that adds retain/release/autorelease statements to your code for you.

This is not a Garbage Collection, and reference counted memory has not disappeared, it has simply been automated. It may sound like a bit of an after thought, but considering how many features in Objective-C are implemented by pre-processing source files before compiling, ARC is really par for the course.

                  Enabling ARC in Your Project

To enable ARC simply set the Objective-C Automatic Reference Counting option in your Xcode project’s Build Settings to YES. Behind the scenes this sets the -fobjc-arc compiler flag that enables ARC.

Including Code that is not ARC Compliant

According to Apple’s documentation: “ARC interoperates with manual reference counting code on a per-file basis. If you want to continue using manual reference counting for some files, you can do so.”
This means some files can use ARC and some files can be spared from it’s magical grasp. Here are the steps for bulk excluding files from ARC at compile time. At the time of writing, many popular libraries are not ARC ready, to get around this follow these steps:
Click on your Project in the Xcode project tree
Click on the Target
Select the Build Phases tab
Expand the Compile Sources section
Select one or more files you want to exclude from ARC
Press the return key
Type -fno-objc-arc
Press the return key again
Each file selected now has a -fno-objc-arc compiler flag set and will be excluded from ARC

Migrating Existing Projects to ARC

Xcode 4.2 provides a conversion tool that migrates existing code to ARC, and helps you manually convert code that cannot be automatically migrated.

1. Open your non-ARC compliant project and go to Edit > Refactor > Convert to Objective-C ARC.

2. Select the build targets and contained files to convert (you exclude files in laters steps too)

3. Run Precheck and press next.

NB: When you press next the LLVM compiler will build the project in order to analyse it. If your project has any errors, you cannot proceed to the next step. If you are opening a project from a previous Xcode version for the first time, remember to Clean.


Tuesday, July 26, 2011

View Controller Life Cycle

View Controllers have a “lifecycle” from loading to unloading, and we have to override its delegate methods according to our requirement.

1.The life cycle starts with alloc and initialization:
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)aBundle;
This is UIViewController’s designated initializer. The UIViewController tries to get its view from the specified .xib file called nibName.
If nibName is nil, it uses the name of the class as the nibName (MyViewController.xib).
The bundle allows you to specify one of a number of different .xib files (localization).
Passing nil for aBundle basically means “look in the Resources folder from Xcode.”
Initializing UIViewController with init is very common, it means nibName is nil & aBundle is nil.
Can I build a UIViewController’s view in code (i.e. w/o a .xib)? Yes. If no .xib is found using mechanism above, UIViewController will call - (void)loadView on itself. loadView’s implementation MUST set the view property in the UIViewController. Don’t implement loadView AND specify a .xib file (it’s undefined what this would mean).

2. viewDidLoad is called after the UIViewController is initialized.
- (void)viewDidLoad;
The viewDidLoad method is only called when the view is first loaded from the Nib file. If the view was already loaded and you push the view again it will not fire again. viewDidLoad is things you have to do once.Whenever I'm adding controls to a view that should appear together with the view, right away, I put it in the ViewDidLoad method. Basically this method is called whenever the view was loaded into memory. So for example, if my view is a form with 3 labels, I would add the labels here; the view will never exist without those forms.
3. Just before the view appears on screen, viewWillAppear is called.
- (void)viewWillAppear:(BOOL)animated;
Your view will probably only get “loaded” once, but it might appear and disappear a lot. So don’t put something in this method that really wants to be in viewDidLoad. Otherwise, you might be doing something over and over unnecessarily.
Use this to optimize performance by waiting until this method (i.e. just before view appears) to kick off an expensive operation (might have to put up a spinning “loading” icon though).
4. viewWillDisappear will be called when you will disappear off screen
- (void)viewWillDisappear:(BOOL)animated {
[superviewWillDisappear:animated]; //callthisinalltheviewWill/Didmethods // let’s be nice to the user and remember the scroll position they were at ... [selfrememberScrollPosition]; //we’llhavetoimplementthis // do some other clean up now that we’ve been removed from the screen
[self saveDataToPermanentStore];
// but be careful not to do anything time-consuming here, or app will be sluggish // maybe even kick off a thread to do what needs doing here
5. There are also “did” versions of both of these method:
- (void)viewDidAppear:(BOOL)animated; - (void)viewDidDisappear:(BOOL)animated;

6.  In low-memory situations, viewDidUnload is called. 
Be sure to release your outlets (or other data tied with the view and its subviews).

7. Now comes to device rotation
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)anOrientation {
return (anOrientation == UIInterfaceOrientationPortrait) || (anOrientation == UIInterfaceOrientationPortraitUpsideDown);
The default is to only allow UIInterfaceOrientationPortrait. This UIViewController’s view is allowed to flip around if the device is turned upside down. There is also UIInterfaceOrientationLandscapeLeft and Right. It is certainly nice to return YES from this method for as many as possible orientations.
But make sure that your view can draw itself “wide and not-tall” as well as “tall and not-wide” if you are going to return YES for the landscape orientations.

View Controller When rotation actually happens
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)anOrientation duration:(NSTimeInterval)seconds;
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)anOrientation; @property UIInterfaceOrientation interfaceOrientation;
The property will have the current orientation when each of the above is called. Stop doing anything expensive (e.g. an animation maybe?) in will and resume it in did.
The best way to handle rotations is to design your view to layout its subviews properly (i.e. set their frames) no matter what the aspect ratio of the view is.
Interface Builder can let you set “struts and springs” to help with layout flexibility. Or the UIView method layoutSubviews can be overridden to do this (outside this course’s scope).