Pages

Monday, October 7, 2013

Atomic vs Nonatomic

In this post I will discuss the difference between (atomic) and (nonatomic).

Atomic

Atomic is the default behaviour for a property; by not explicitly setting the above property as nonatomic, it will be atomic.
An atomic property adds a level of thread safety when getting or setting values. That is, the getter and setter for the property will always be fully completed regardless of what other threads are doing. The trade-off is that these properties will be a little slower to access than a nonatomic equivalent.

Nonatomic

Nonatomic properties are not thread safe, and will return their properties directly. This will be faster than atomic properties, but obviously carries some risk if precautions aren’t made.

When is it Appropriate to Use Nonatomic?

One thing I’ve noticed while following Objective-C tutorials and articles is that nonatomic is used most of the time. So if nonatomic is so risky, why is it used so often?
It’s all about performance. An atomic property’s getter and setter, conceptually, looks something like this:
Whereas a nonatomic property getter and setter looks something like this:
It’s easy to see how the nonatomic implementation is going to be more light weight, but it does mean you have a responsibility to ensure problems don’t arise. Some articles I’ve read recommend keeping things atomic until performance becomes a problem, while others recommend the opposite.
In any event, if you decide to create a nonatomic property, here are some tips for keeping things thread safe:
  • Use immutable objects where possible. For example, rather than creating an NSMutableArray, create an immutable NSArray. Whenever you need to add an object to it, create a mutable copy first and do what you need to do, then replace the entire property in one hit rather than tacking on another value to the end.
  • You can wrap potentially problematic sections of code with @synchronized.
  • UI code can always be nonatomic because UI code always happens on the main thread of the application.

Thursday, September 12, 2013

Creating a Static Library in iOS

A static library is a package of classes, functions, definitions and resources, which you can pack together and easily share between your projects.
In this tutorial you will get hands-on experience creating your own universal static library and use this .

Why Use Static Libraries?

You might want to create a static library for different reasons. For example:
    •    You want to bundle a number of classes that you and/or your colleagues in your team use regularly and share those easily around.
    •    You want to be able to keep some common code centralized so you can easily add bugfixes or updates.
    •    You’d like to share a library with a number of people, but not allow them to see your code.
    •    You’d like to make a version snapshot of a library that develops over time.
        

Getting Started

Launch Xcode, and choose File\New\Project. When the Choose a template dialog appears, select iOS\Framework & Library\Cocoa Touch Static Library, as shown below:



Click Next. In the project options dialog, type MathUtils as the product name. Then, enter a unique company identifier and make sure Use Automatic Reference Counting is checked, and Include Unit Tests is unchecked, as so:



Click Next. Finally, choose a location where you’d like to save your new project, and click Create.
Xcode has just created a ready to use static library project, and even added a class MathUtils for you.

Next, paste the following declarations below the line @interface MathUtils : NSObject

- (NSArray *) fibonacci:(NSInteger) n;
- (NSInteger) factorial:(NSInteger) n;

Nothing fancy, just our method declarations. When we distribute the library file, this header file MUST be included as well.

One thing I should point out here is don’t make every iVar public! As a newer developer you might think it’s cool to make a public property out of EVERYTHING. This is bad form and here is where it will bite you. You don’t want the external world being able to muck with things that you don’t want them to.

And Now the .m file for the implementation:

- (NSArray *) fibonacci:(NSInteger) n
{

    NSMutableArray *fib = [NSMutableArray array];

    int a = 0;
    int b = 1;
    int sum;
    int i;

    for (i=0;i < n;i++)
    {
        [fib addObject:[NSNumber numberWithInt:a]];
        sum = a + b;
        a = b;
        b = sum;
    }

    return (NSArray *) fib;
}

- (NSInteger) factorial:(NSInteger) n
{
    if ( n <= 1 )
        return 1;
    else
        return n * [self factorial:( n-1 )];

}

This code should be very familiar and that’s it for our static library.

Rather than a .app or a .ipa file, a static library has the .a extension. You can find the generated static library in the Products folder in the project navigator. Right-click or control-click libMathUtils.a and select Show in Finder in the contextual menu.




Xcode will open the folder in Finder, where you’ll see something like this:



Now drag this file into a new folder that you create where you will be bundling all of your library files. I just created a folder on my desktop named MathLibrary. Now, do the same with all of the .h files. In our case, just copy MathUtils.h into this new directory. Your directory structure should now look like:

MathLibrary

|- libMathUtils.a

|- MathUtils.h

Linking Your Library In A New Project

So now that you have built your shiny new static library, it’s time to test it out in another application. XCode has a number of ways to actually achieve this, but I will show the most simple and Mac-like… drag and drop .

Create a new View-Based project (or whatever it doesn’t really matter). I named mine MathTest.
Now, just drag this folder into the project and XCode will set up all of the linking automagically. When prompted to copy,The final step is to add the -ObjC linker flag. The linker tries to be efficient about only including needed code, which can sometimes exclude static library code. With this flag, all the Objective-C classes and categories in the library are loaded properly.You should now see the .a file along with the header files in the new project.

Click on the Build Settings tab, and locate the Other linker Flags setting, as shown below:




In the popover, click on the + button and type -ObjC, as such:



Using The Static Library Code

Now that all of the linking is set up, you just use your library like any other class. In the App Delegate class of my test project, I simple did this:

#import "MathUtils.h"

And in the applicationDidFinishLaunchingMethod…

MathUtils *mFunctions = [[MathUtils alloc] init] ;
NSLog(@"fibonacci for 10 = %@", [mFunctions fibonacci:10]);
NSLog(@"10! = %d",[mFunctions factorial:10]);

This of course prints out:

fibonacci for 10 = (
    0,
    1,
    1,
    2,
    3,
    5,
    8,
    13,
    21,
    34
) 10! = 3628800
And there it is! Static library code being executed in a totally separate project.

Hopefully this tutorial has given you some insight into the basic concepts of static libraries and how to use them in your own apps.

Wednesday, August 28, 2013

Same Xcode Project Create Multiple Products

Some times you need to build two versions of your iPhone application(i.e lite and full version) from the same Xcode project. So one way is to make two copies of your Xcode project and manage both independently which is not a good way. Because when you have to change a little in your iPhone application, you have to change in both copies of your Xcode projects. So its not easily manageable for anyone to change a line of code in both codes of one application. So following this tutorial, you can make different applications from one source Xcode project!

Xcode is really a good IDE which provide lot of features. Everyday I come across to know more about Xcode features while building iPhone applications. So today I am going to share another most important feature of Xcode which helps you when you are thinking to create two iPhone application but with same project. So theme of this tutorial is to, create one application in Xcode and generator two builds(binary) form same code. In other words, you don’t have to manage two copies of your application. Just create one application and generator two copies of build(binary) files for apple store.
So let just start without going any further discussion. What I will do in this tutorial, create a project in Xcode and place three buttons on controller view. One button will display for lite version and one button will display on full version.

So lets start:



1. Create a “View-Based Application” project in Xcode and named it “MultipleProducts”

2. In your ViewController.h file write the following code for linking with Interface builder
IBOutlet UIButton *buttonOne;
IBOutlet UIButton *buttonTwo;

3. Open ViewController.xib file in interface builder and place two buttons on the view. Now select two buttons and set hidden property to true.

4. Now map those buttons with ViewController class.

5. Open ViewController.m file and write down following code in viewDidLoad method ( I will explain this code later):
#ifdef LITEVERSION
buttonOne.hidden = NO;
#endif
#ifdef FULLVERSION
buttonTwo.hidden = NO;
#endif

6. Duplicate your target MultipleProducts and  Rename the duplicate file(HelloWorld copy) to MultipleProductsLite (see figure)



7. Now you will see “MultipleProductsLite-Info.plist” and “MultipleProductsLite-Info copy.plist” in your Resources folder. Rename “MultipleProductsLite-Info copy.plist” to “MultipleProductsLite-Info.plist” . To check if everything goes right, select “MultipleProductsLite” application from target and clicked on “info” from Xcode and chosse MultipleProductsLite-Info.plist for this target.




8. Last step, clicked on "build setting” and type “OTHER_CFLAGS” in “Setting” column and type -DLITEVERSION in value column. Close info window.



9. Now select “MultipleProducts” form target  and right clicked on it to select “build setting” and type “OTHER_CFLAGS” in “Setting” column and type -DFULLVERSION in value column.

Now its time to build full version for MultipleProducts,  Now run the project and see the result.

Now to build for lite version of the MultipleProducts, select the MultipleProducts copy and run the project and see result



Keep Coding…

Monday, August 26, 2013

How to Avoid Getting Your App Rejected

Apple’s App Store review process is designed to keep the app ecosystem healthy and to protect users from low-quality or hostile apps. And the system mostly works. But sometimes an app is rejected for reasons you might not expect, and it can force developers to scramble to either push back launch dates or even have to redevelop key features.
Before you head down that road, here are some reasons apps get rejected by the App Store that you should consider before you submit your next app: 

1.     Use of the word “beta” or otherwise indicating that your app is unfinished
Google has made it a standard industry practice to launch services into indefinite “beta,” but Apple can be quite strict about any indication that an app is unfinished or not yet ready for prime time. We have seen apps get rejected for being labeled “Beta,” “Preview,” and even “Version 0.9.”

2.     Long load time
All mobile operating systems – iOS, Android, and even Windows – enforce a maximum app startup time. For iOS, the limit is about 15 seconds, and if your app isn’t running by then the operating system will kill it.
But even if your app loads within the limits during your local testing, slower network connections, slower hardware, and other differences in the environment may cause your app to start too slowly during the review process. So don’t rely on the iOS simulator alone – be sure to test on actual hardware, and keep a few older phones around to ensure all users have a snappy startup.
Remember, your app’s load time is your first chance to impress your users.

3.     Linking to outside payment schemes
Apple requires that all digital content be sold through the built-in iTunes-based in-app purchasing mechanism. This applies to one-time purchases as well as digital subscriptions. If your app accepts other payment mechanisms for digital content, you can be sure it will be rejected. This is the reason the Kindle app does not allow users to purchase new books.
One important subtlety is that this rule applies even to Web pages linked to from your app. The Dropbox app was famously rejected by Apple because the Web-based login screen contained a link to purchase additional space. This not only affected the Dropbox app, but all apps that used the Dropbox SDK as well!
So double check your workflow to ensure that all purchasing goes through the user’s iTunes account, or is removed altogether. This rule does not apply to non-digital services or merchandise, which is why Apply doesn’t get a cut of your Uber rides or hotel rooms booked through an app.

4.     Do not mention other supported platforms
This rule is not unique to Apple – none of the curated app marketplaces like it when apps mention rival platforms by name. So if your app is also available on Windows or Android, advertise that on your Web site, not in the app or the app store description.

5.     Localization glitches
The users of your mobile app will be everywhere, not just in the city or country the development was done.
Even if you haven’t localized your app for multiple languages, it will look amateur if 300 YEN comes out looking like $300.00 for in-app purchases. Use add-ons such asNSNumberFormatter or Invariant Culture and a simulator to test the user experience in different locales to make sure dates and other data conform to the user’s location.
For instance, we’ve seen European apps fail to handle negative values for latitude and longitude, and therefore not pass review in Cupertino, which is at Longitude -122.03. Make sure your app works at all points on the map, and especially check that your lat/long math for groups of points span the positive/negative boundaries of the prime meridian and the equator.

6.     Improper use of storage and filesystems
Soon after iOS 5.1 was released, Apple rejected an app update because developers had unpacked the 2MB database from the app bundle into the filesystem, violating the iCloud ideal of backing up only user-generated content.
Any data that can be re-generated because it is static, shipped with the application or is easily re-downloaded from a remote server, should not be able to be backed up. For non-user data, choose a cache storage location or mark with a “do not backup” attribute.

7.     Crashes from users denying permissions
In iOS 6 users must give permission for apps to access the address book, photo gallery, location, calendar, reminders, Bluetooth, Twitter and Facebook accounts. If the user chooses to deny an app access to any of these services, Apple requires that the app continue to function anyway.
This will certainly be tested during validation and will be an automatic rejection if it fails to work properly. You should test all combinations of “allow” and “deny” for all the data your app uses, including if the user allows access but later denies it in Settings.

8.     Improper use of icons and buttons
Many an iOS app have been rejected because of small UI issues that had nothing to do with performance or functionality. Make sure the built-in Apple icons and buttons are uniform in appearance and functionality by using a standard UIButtonBarSystemItem and familiarize yourself with Apple’s Human Interface Guidelines.
For instance, you don’t want to use the “compose” icon for anything other than referring to content creation. Apple engineers want apps to behave in predictable ways and are therefore understandably strict about this.

9.     Misuse of trademarks and logos
Don’t use trademarked material or Apple icons or logos anywhere in your app or product images. This includes using icons that feature a drawing of an iPhone! We’ve also seen apps get denied for having trademarks in the keywords of the app.
The flipside of this is that you should be sure your app does not obscure the attribution information in any embedded maps – this is also an automatic rejection.
  
If your app does get rejected, don’t panic — address the issue and resubmit.The best approach is to avoid rejection in the first place. So, study the submission guidelines and focus on building a high-quality app. Your users will thank you for it.

Keep Coding...

Friday, August 23, 2013

How to make your iOS app UI appealing.

Now a days apple is releasing their iOS version after every 6 month with having lots of drastic changes. Apple is also concentrating more on UI along with the functionality of iOS so that user can get feel of retina display device.

In my iOS career i have also developed some good UI appealing app and now want to share some key element which need to taken care of while designing app like this.

1) While starting for any app first clear its requirement, and try to draw that requirement in terms of wireframe by using software like Balsamiq and other. which will give you more clear app development idea and also your client knows that what he will be getting after few months.

2) Try to use .xib rather than using Programmatic way to add controls on view.

3) Check with your graphics designer that he is designing images for you in Retina display size.

For iPhone and iPod touch launch images, include the status bar region. Create launch images of these sizes:
  • 320 x 480 pixels
  • 640 x 960 pixels (Retina 3.5 Full Screen) 
  • 640 x 1136 pixels (Retina 4 Full Screen) 
For iPad launch images, do not include the status bar region. Create launch images of these sizes:
  • For portrait:
    • 768 x 1004 pixels
    • 1536 x 2008 pixels (Retina Display)
  • For landscape:
    • 1024 x 748 pixels
    • 2048 x 1496 pixels (Retina Display)
 For iPhone and iPod touch create Icon images of these sizes:
  • 57 x 57
  • 114 x 114 (Retina Display)
 For iPad create Icon images of these sizes:
  •  72 x 72
  • 144 x 144 (Retina Display)
 You can get more details on this from developer.apple.com by using your developer account.

4) Before starting designing exact view controllers first decide the button size that you want to use in your application. keep the button or other control ratio same on every view of your application so that user will get feel of navigating in same app.

5) Try to use default controls provided by apple if you don't have graphics for application.

6) Try to use custom controls if you have really clean and neat graphics available.

7) Try to use AutoLayout for designing both Retina 3.5 Full Screen and Retina 4 Full Screen.

8) Whenever you are trying to deal with large number of sequential data coming from server try to use UITableview to represent it. UITableview is having lot of customization methods which will help you to design good UI.

9) Avoid excessive use of UIScrollview in your application which will increase user confusion.

10) Try to reduce number of activity indicator in your application which will lead bad user experience.

Keep Coding..

Thursday, August 22, 2013

Coding style for iOS app

Coding standard can be a great benefit as it makes it easy to read any code, and is a good practices which leads to less defects.

As writing a code according to coding guidelines is really very impressive and effective as well as very important.
Still many of us don’t follow any, here we have a very small and crisp idea of coding standard for iOS developers.
Contents

• Interface Files
• Implementation Files
• UIControls Prefixes List
• Before Deliver Source Code

Interface Files

The Interface Files/ .h files are header files. It is called header file because it only contains the ‘head’ or a class, in other words, all the properties and functions that any other outside class should know about, the ‘public face’ of a class. It does not contain implementation logics at all.
Standard to follow for .h file -
The interface files should be as small as possible and serve as a reference for what the class does and how to interact with it
• System imports go before project imports
• Don’t import anything that’s not needed for defining the interface
• Only expose the minimum necessary for other classes to interact. Everything else goes into implementation file
• Comment any non-obvious method

// MyClass.h

import
#import "MyOtherClass.h"

@interface MyClass : NSObject
@property (nonatomic, retain) MyOtherClass *blog;
@property (nonatomic, readonly, retain) NSArray *readonlyThing;
@property (nonatomic, assign) id delegate;
/**
Explain in a few words about the methods
*/
- (void)myClassMethods;
@end


Implementation Files

Implementation Files/.m file contains all the implementation details of all the functions declared in .h and more. It also contains declaration and implementation of private functions that outside classes cannot use, or should not care about.
Standard to follow for .m file -
• If the interface file has declared readonly properties, redeclare them as readwrite to be able to use the accessors
• Declare any internal variable and methods in the implementation
• dealloc is the first method, followed by initialization methods (If not using ARC)
• Use “#pragma mark -” to group methods into sections

// MyClass.m

#import "MyClass.h"
#import "ClassDependencies.h"

@interface MyClass ()
@property (nonatomic, retain) NSArray *readonlyThing;
/** Private methods */
- (void)prepareStuff;
@end
@implementation MyClass {
NSMutableArray *_things;
BOOL _flag;
}
@synthesize blog = _blog;
@synthesize delegate = _delegate;
@synthesize readonlyThing = _readonlyThing;
- (void)dealloc {
[super dealloc];
self.blog = nil;
self.readonlyThing = nil;
[_things release];
// ...
}
- (void)init {
self = [super init];
if (self) {
// Initialize
_things = [[NSMutableArray alloc] init];
}
return self;
}
#pragma mark - Public methods
- (void)myClassMethods {
[self prepareStuff];
// Do actual stuff
}
#pragma mark - Private methods
- (void)prepareStuff {
// Prepare stuff
// self.readonlyThing = ...
}
@end


UIControls Prefixes List

Here goes some common prefixes for UIControls, that we should use as a prefix in declaration of UIControls Object, this make variables readable and easy to find out.

UIControl                                Prefix
UILabel                                  lbl
UIButton                                 btn
UISegmentControl                         segCntrl
UITextfield                              txtFld
UISlider                                 sldr
UISwitch                                 switch
UIActivityIndicatorView                  ai
UIProgressView                           pv
UITableView                              tblView
UIImageView                              imgView
UITextView                               txtView
UIWebView                                webView
MKMapView                                mapView
UIScrollView                             srlView
UIDatePicker                             datePickerp
UIPickerView                             picker
UIView                                   view
UIWindow                                 window
UINavigationBar                          navBar
UINavigationItem                         navItem
UISearchBar                              searchbar
UIToolBar                                toolbar
UITabBar                                 tabbar


Before Deliver Project

Before We deliver our project to client, we should take care of following things.

• Check for whitespace.
• No NSLog in commits.
• No commented out code.
• Don’t avoid compiler warnings.
• Analyze Source Code and handle memory leaks.
• Source Code should be proper documented.

Happy Coding.. 

Wednesday, May 29, 2013

Accept buddy request in xmpp client


You will receive the subscription in function didReceivePresence.


- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)
 presence {

    // a buddy went offline/online

    NSString *presenceType = [presence type];            // online/offline
    NSString *myUsername = [[sender myJID] user];
    NSString *presenceFromUser = [[presence from] user];

    if (![presenceFromUser isEqualToString:myUsername]) {

        if ([presenceType isEqualToString:@"available"]) {

            [_chatDelegate newBuddyOnline:[NSString stringWithFormat:
@"%@@%@" , presenceFromUser, kHostName]];
               NSLog(@"presence user is %@",presenceFromUser);

        } 

        else if  ([presenceType isEqualToString:@"unavailable"]) {

            [_chatDelegate buddyWentOffline:[NSString stringWithFormat:
@"%@@%@" , presenceFromUser, kHostName]];
            NSLog(@"presence user is invisible %@",presenceFromUser);

        }
        else if  ([presenceType isEqualToString:@"subscribe"]) {

        NSXMLElement *presence = [NSXMLElement elementWithName:@"presence"];
        [presence addAttributeWithName:@"type" stringValue:@"subscribed"];
        [presence addAttributeWithName:@"to" stringValue:[presence fromStr]];
        [presence addAttributeWithName:@"from" stringValue:@"you@host"];
        [[self xmppStream] sendElement:presence];

        }

    }
}

How to blinking the text of UITextview

CABasicAnimation *basic=[CABasicAnimation animationWithKeyPath:@"transform"];
[basic setToValue:[NSValue valueWithCATransform3D:CATransform3DMakeScale (1.25, 1.25, 1.25)]];
[basic setAutoreverses:YES];
[basic setRepeatCount:MAXFLOAT];
[basic setDuration:0.25];
[self.imgVArrow.layer addAnimation:basic forKey:@"transform"];

How to get Screen Shot of current ViewController



    UIGraphicsBeginImageContext(self.view.bounds.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData * data = UIImagePNGRepresentation(image);
    [data writeToFile:@"foo.png" atomically:YES];