Saturday, December 22, 2012

Variable property attributes or Modifiers in iOS

Variable property attributes or Modifiers

Property Attributes Indicate Data Accessibility and Storage Considerations

Use Accessor Methods to Get or Set Property Values

01. atomic //default
02. nonatomic
03. strong=retain //default
04. weak= unsafe_unretained
05. retain
06. assign //default
07. unsafe_unretained
08. copy
09. readonly
10. readwrite         //default

01. atomic 
-Atomic means only one thread access the variable(static type).
-Atomic is thread safe.
-but it is slow in performance
-atomic is default behavior
-Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to 
ensure that another thread doesn't interfere with the correct setting/getting of the value.
-it is not actually a keyword.
Example :

@property (retain) NSString *name;

@synthesize name;

02. nonatomic
-Nonatomic means multiple thread access the variable(dynamic type).
-Nonatomic is thread unsafe.
-but it is fast in performance
-Nonatomic is NOT default behavior,we need to add nonatomic keyword in property attribute.
-it may result in unexpected behavior, when two different process (threads) access the same variable at the same time.


@property (nonatomic, retain) NSString *name;

@synthesize name;


Suppose there is an atomic string property called "name", and if you call [self setName:@"A"] from thread A, 
call [self setName:@"B"] from thread B, and call [self name] from thread C, then all operation on different thread will be performed serially which means if one thread is executing setter or getter, then other threads will wait. This makes property "name" read/write safe but if another thread D calls [name release] simultaneously then this operation might produce a crash because there is no setter/getter call involved here. Which means an object is read/write safe (ATOMIC) but not thread safe as another threads can simultaneously send any type of messages to the object. Developer should ensure thread safety for such objects.

If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, Either one of A, B or C will execute first but D can still execute in parallel.

03. strong (iOS4 = retain )
-it says "keep this in the heap until I don't point to it anymore"
-in other words " I'am the owner, you cannot dealloc this before aim fine with that same as retain"
-You use strong only if you need to retain the object.
-By default all instance variables and local variables are strong pointers.
-We generally use strong for UIViewControllers (UI item's parents)
-strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you  when you are done with it.Using the keyword strong means that you own the object.


@property (strong, nonatomic) ViewController *viewController;

@synthesize viewController;

04. weak (iOS4 = unsafe_unretained )
-it says "keep this as long as someone else points to it strongly"
-the same thing as assign, no retain or release
-A "weak" reference is a reference that you do not retain.
-We generally use weak for IBOutlets (UIViewController's Childs).This works because the child object only 
needs to exist as long as the parent object does.
-a weak reference is a reference that does not protect the referenced object from collection by a garbage collector.
-Weak is essentially assign, a unretained property. Except the when the object is deallocated the weak pointer is automatically set to nil

Example :

@property (weak, nonatomic) IBOutlet UIButton *myButton;

@synthesize myButton;


Imagine our object is a dog, and that the dog wants to run away (be deallocated).
Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached.
Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it.
As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out.
When we use weak?
The only time you would want to use weak, is if you wanted to avoid retain cycles 
(e.g. the parent retains the child and the child retains the parent so neither is ever released).

05. retain = strong
-it is retained, old value is released and it is assigned
-retain specifies the new value should be sent -retain on assignment and the old value sent -release
-retain is the same as strong.
-apple says if you write retain it will auto converted/work like strong only.
-methods like "alloc" include an implicit "retain"


@property (nonatomic, retain) NSString *name;

@synthesize name;

06. assign 
-assign is the default and simply performs a variable assignment
-assign is a property attribute that tells the compiler how to synthesize the property's setter implementation
-I would use assign for C primitive properties and weak for weak references to Objective-C objects.


@property (nonatomic, assign) NSString *address;

@synthesize address;

07. unsafe_unretained

-unsafe_unretained is an ownership qualifier that tells ARC how to insert retain/release calls
-unsafe_unretained is the ARC version of assign.


@property (nonatomic, unsafe_unretained) NSString *nickName;

@synthesize nickName;

08. copy
-copy is required when the object is mutable.
-copy specifies the new value should be sent -copy on assignment and the old value sent -release.
-copy is  like retain returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments.
-if you use copy then you still need to release that in dealloc.
-Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other 
owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.


@property (nonatomic, copy) NSArray *myArray;

@synthesize myArray;

09. readonly
-declaring your property as readonly you tell compiler to not generate setter method automatically.
-Indicates that the property is read-only.
-If you specify readonly, only a getter method is required in the @implementation block. If you use the @synthesize directive in 
the @implementation block, only the getter method is synthesized. Moreover, if you attempt to assign a value using the dot syntax, 
you get a compiler error.


@property (nonatomic, readonly) NSString *name;

@synthesize name;

10. readwrite 
-setter and getter generated.
-Indicates that the property should be treated as read/write.
-This attribute is the default.
-Both a getter and setter method are required in the @implementation block. If you use the @synthesize directive in the implementation 
block, the getter and setter methods are synthesized.


@property (nonatomic, readwrite) NSString *name;

@synthesize name;

Tuesday, November 6, 2012

Thread in iOS (Theory)

Thread in iOS

Threads are one of several technologies that make it possible to execute multiple code paths concurrently inside a single application. 
Threads are a relatively lightweight way to implement multiple paths of execution inside of an application.

Inside each program, however, exists one or more threads of execution, which can be used to perform different tasks simultaneously.
The system itself actually manages these threads of execution, scheduling them to run on the available cores and preemptively interrupting them as needed to allow other threads to run.

From a technical standpoint, a thread is a combination of the kernel-level and application-level data structures needed to manage the execution of code.
threads provide a way to increase performance in some types of applications.

  • The term thread is used to refer to a separate path of execution for code.
  • The term process is used to refer to a running executable, which can encompass multiple threads.
  • The term task is used to refer to the abstract concept of work that needs to be performed.

1.Cocoa threads : Cocoa implements threads using the NSThread class. Cocoa also provides methods on NSObject for spawning new threads and executing code on already-running threads.

2.POSIX threads : POSIX threads provide a C-based interface for creating threads. If you are not writing a Cocoa application, this is the best choice for creating threads.

3. Multiprocessing Services : Multiprocessing Services is a legacy C-based interface used by applications transitioning from older versions of Mac OS. Instead, you should use the NSThread class or POSIX threads.

Threads are relatively expensive to create in terms of memory and time.
Thread States : After starting a thread, the thread runs in one of three main states: running, ready, or blocked.
If a thread is not currently running, it is either blocked and waiting for input or it is ready to run but not scheduled to do so yet.
Thread entry-point : When you create a new thread, you must specify an entry-point function/method for that thread.

Run Loop  : 
A run loop is an event processing loop that you use to schedule work and coordinate the receipt of incoming events. The purpose of a run loop is to keep your thread busy when there is work to do and put your thread to sleep when there is none.
A run loop puts its thread to sleep when there is nothing to do, it eliminates the need for polling, which wastes CPU cycles and prevents the processor itself from sleeping and saving power.
To configure a run loop, all you have to do is launch your thread, get a reference to the run loop object, install your event handlers, and tell the run loop to run.
If you plan to create long-lived secondary threads, however, you must configure the run loop for those threads yourself.
Thread Synchronization
Locks (NSLock class)
Locks provide a brute force form of protection for code that can be executed by only one thread at a time. The most common type of lock is mutual exclusion lock, also known as a mutex. When a thread tries to acquire a mutex that is currently held by another thread, it blocks until the lock is released by the other thread. 
You can use locks to protect a critical section of your code, which is a segment of code that only one thread at a time is allowed access.

Conditions (NSCondition Class)
A condition acts as a gatekeeper, blocking a given thread until the condition it represents becomes true. When that happens, the condition releases the thread and allows it to continue.

Atomic operations
Atomic operations are another way to protect and synchronize access to data. Atomic operations offer a lightweight alternative to locks in situations where you can perform mathematical or logical operations on scalar data types. Atomic operations use special hardware instructions to ensure that modifications to a variable are completed before other threads have a chance to access it.

Inter-thread Communication
At some point, communication between threads becomes necessary. 
Creating a multithreaded application is hard. Even if you are very careful and lock shared data structures at all the right junctures in your code, your code may still be semantically unsafe.
A thread’s job is to do work for your application, but if the results of that job are never used, what good is it? so you need a way to get information from one thread to another.
There are many ways to communicate between threads.
1.Direct messaging
This capability means that one thread can essentially execute a method on any other thread.

2.Global variables, shared memory, and objects

Another simple way to communicate information between two threads is to use a global variable, shared object, or shared block of memory.

Shared variables must be carefully protected with locks or other synchronization mechanisms to ensure the correctness of your code. Failure to do so could lead to race conditions, corrupted data, or crashes.

3.Conditions (NSCondition Class)

Conditions are a synchronization tool that you can use to control when a thread executes a particular portion of code. 

A thread waiting on a condition remains blocked until that condition is signaled explicitly by another thread.
4. Run loop
Run loop sources put your thread to sleep automatically when there is nothing to do, which improves your thread’s efficiency.

5.Ports and sockets
Ports and sockets can be used to communicate with external entities, such as other processes and services. so your thread sleeps when there is no data waiting on the port.

6.Message queues
7.Cocoa distributed objects

Thread Management :

Every application starts with a single thread, which runs the application's main function. Applications can spawn additional threads, each of which executes the code of a specific function.
When an application spawns a new thread, that thread becomes an independent entity inside of the application's process space. Each thread has its own execution stack and is scheduled for runtime separately by the kernel. A thread can communicate with other threads and other processes, perform I/O operations, and do anything else you might need it to do. Because they are inside the same process space, however, all threads in a single application share the same virtual memory space and have the same access rights as the process itself.

Thread Costs:
Threading has a real cost to your program (and the system) in terms of memory use and performance. Each thread requires the allocation of memory in both the kernel memory space and your program’s memory space. 
1. Kernel data structures [ 1 kb] : This memory is used to store the thread data structures and attributes, much of which is allocated as wired memory and therefore cannot be paged to disk.

2. Stack space [512 KB (secondary threads) 8 MB (OS X main thread) 1 MB (iOS main thread) ] :  The minimum allowed stack size for secondary threads is 16 KB and the stack size must be a multiple of 4 KB.

3. Creation time [90 microseconds] : This value reflects the time between the initial call to create the thread and the time at which the thread’s entry point routine began executing.

Creating a Thread :

There are two ways to create a thread
Use the detachNewThreadSelector:toTarget:withObject: class method to spawn the new thread. (is supported in all versions of OS X)
Create a new NSThread object and call its start method. (Supported only in iOS and OS X v10.5 and later.)

* Both techniques create a detached thread in your application. A detached thread means that the thread’s resources are automatically reclaimed by the system when the thread exits.

1. Create Thread using "detachNewThreadSelector:toTarget:withObject " method
To detach a new thread, you simply provide the name of the method (specified as a selector) that you want to use as the thread’s entry point, the object that defines that method, and any data you want to pass to the thread at startup.

Example :
[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil];

2. Create Thread using " initWithTarget:selector:object " method

This method takes the exact same information as the detachNewThreadSelector:toTarget:withObject: method and uses it to initialize a new NSThread instance. It does not start the thread, however. To start the thread, you call the thread object’s start method explicitly.
Example :

NSThread* myThread = [[NSThread alloc] initWithTarget:self

[myThread start];  // Actually create the thread
[myThread cancel];
[NSThread exit];

3. Create Background thread with NSObject class

The performSelectorInBackground:withObject: method creates a new detached thread and uses the specified method as the entry point for the new thread.if you have some object ( myObj) and that object has a method called doSomething that you want to run in a background thread.


[myObj performSelectorInBackground:@selector(doSomething) withObject:nil];

* this method is the same as if you called the detachNewThreadSelector:toTarget:withObject: method of NSThread with the current object.

Autorelease Pool

Note : you would need to set up an autorelease pool (if you were not using garbage collection) and configure the thread’s run loop if you planned to use it. The autorelease pool catches any objects that are autoreleased from that thread.
Because the top-level autorelease pool does not release its objects until the thread exits, long-lived threads should create additional autorelease pools to free objects more frequently.

- (void)doSomething {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
*** code that should be run in the new thread goes here ***
[pool release];

Thread Attributes

1. change thread stack size

Allocate and initialize an NSThread object (do not use the detachNewThreadSelector:toTarget:withObject: method). Before calling the start method of the thread object, use the setStackSize: method to specify the new stack size.

Thread Types:

1.Detached threads

Most high-level thread technologies create detached threads by default. In most cases, detached threads are preferred because they allow the system to free up the thread’s data structures immediately upon completion of the thread. Detached threads also do not require explicit interactions with your program.

2.Joinable threads

You can think of joinable threads as akin (similar) to child threads.Although they still run as independent threads, a joinable thread must be joined by another thread before its resources can be reclaimed by the system.

* At application exit time, detached threads can be terminated immediately but joinable threads cannot. Each joinable thread must be joined before the process is allowed to exit. Joinable threads may therefore be preferable in cases where the thread is doing critical work that should not be interrupted, such as saving data to disk.

Thread Priority:

you can use the setThreadPriority: class method of NSThread to set the priority of the currently running thread.

It is generally a good idea to leave the priorities of your threads at their default values. Increasing the priorities of some threads also increases the likelihood of starvation among lower-priority threads.

Terminating a Thread:

The recommended way to exit a thread is to let it exit its entry point routine normally. Killing a thread prevents that thread from cleaning up after itself. 

Using the @synchronized Directive

The @synchronized directive is a convenient way to create mutex locks on the fly in Objective-C code.


- (void)myMethod:(id)anObj
        // Everything between the braces is protected by the @synchronized directive.


Grand Central dispatch (Asynchronous Task) / NSOperations

Important: GCD is a C level API; it does not catch exceptions generated by higher level languages. Your application must catch all exceptions before returning from a block submitted to a dispatch queue.

Wednesday, September 12, 2012

Model-View-Controller (MVC) design pattern in iPhone

Model-View-Controller (MVC) :A design pattern in which the model (any data in your program), the view (what the user sees), and the controller (a layer that handles all interaction between the view and model) are separated in such a manner that modifying either the view or model component of your program has no effect on one another.

Model :The model contains the data.
View : The view displays information contained in the model.
Controller : the controller is responsible for accessing data from the model and displaying it on the view.

-------------------------- More Details with Example Got from SO--------------------------

Model : is related to a data which we have regarding our application's objects. Example : Application of a Person Contact Details than, Each Person on in Contact  will be having it'e own attributes (Name, Address etc.) and that will be saved inside Person model.
Controller : is something which controls UI updates. It keeps a reference to Person model and checks for any changes in model, If there is than change the View of that particular person. And it keeps checking for any UI input so it can change data inside Model.
View : This is fairly obvious View is all about UIView, What we see on screen.

Below is snap shot, how I follow MVC in my applications

Apple Says " The Model-View-Controller (MVC) design pattern assigns objects in an application one of three roles: model, view, or controller. The pattern defines not only the roles objects play in the application, it defines the way objects communicate with each other. Each of the three types of objects is separated from the others by abstract boundaries and communicates with objects of the other types across those boundaries. The collection of objects of a certain MVC type in an application is sometimes referred to as a layer—for example, model layer.

MVC is central to a good design for a Cocoa application. The benefits of adopting this pattern are numerous. Many objects in these applications tend to be more reusable "

Model Objects 
Model objects encapsulate the data specific to an application and define the logic and computation that manipulate and process that data.

View Objects
A view object is an object in an application that users can see. A view object knows how to draw itself and can respond to user actions. A major purpose of view objects is to display data from the application’s model objects and to enable the editing of that data. 

Controller Objects
A controller object acts as an intermediary between one or more of an application’s view objects and one or more of its model objects. Controller objects are thus a conduit through which view objects learn about changes in model objects and vice versa. Controller objects can also perform setup and coordinating tasks for an application and manage the life cycles of other objects.

Sunday, July 15, 2012

How to add Shadow,Border and Round corner to View programatically

here is simplest way what I do, When I need to add Shadow, Border or Round Corners Effects on any view

in ViewController.h

1. add QuartzCore.framwork in your project

2. add the UIView in XIB via Interface Builder

3. create UIView's IBOutlet and Hook-up with it
@property (weak, nonatomic) IBOutlet UIView *backgoundWall;

in ViewController.m

4. import QurtzCore header file.
#import <QuartzCore/QuartzCore.h>

3. synthesise the View property variable
@synthesize backgoundWall;

4. in viewDidLoad method add Shadow 

- (void)viewDidLoad
    [super viewDidLoad];    

    backgoundWall.layer.shadowColor =[UIColor blackColor].CGColor;
    backgoundWall.layer.shadowRadius =3.0;
    backgoundWall.layer.shadowOpacity =0.8;
    backgoundWall.layer.cornerRadius =5.0;
    backgoundWall.layer.shadowOffset =CGSizeMake(0, 7);
    backgoundWall.layer.borderColor = [UIColor lightGrayColor].CGColor;
    backgoundWall.layer.borderWidth =2.0;

5. Here is the result screen

Cheers!! We did it.

I would love to here you feedback!!

Saturday, June 2, 2012

Why we use #pragma mark in Objective-C/iPhone code and How to do that?

1. Why :  use pragma mark to help you organise your code for yourself  

Let! me make it more clear, When we work on huge projects and our classes contains tons of lines of code.
it's hard to manage all the methods specially when you are looking for any desired method and you need to scroll all the way again and again.

So #pragma is the way to organise the code, and provide you, Overview of the class showing all the methods, constants, properties etc.

Note: it doesn't affect anything on your code, just for the organising code

2. How : It's pretty simple when you start writing code just add #pragma above method or block every time when you need it.

Example :

#pragma mark - label name

so let's I have some life cycle methods of view controller then I will do like this

#pragma mark - ViewController's LIfe Cycle Methods

3. Here is Example code snip :


#pragma mark - ViewController's LIfe Cycle Methods

- (void)viewDidLoad{
    [super viewDidLoad];

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];    

#pragma mark - Button Click methods

- (IBAction)goButtonPressed:(id)sender {    
    readMeViewController = [[ReadMeViewController alloc] initWithNibName:@"ReadMeViewController" bundle:nil];
    readMeViewController.readMeControllerDelegate = self;
    [self.navigationController pushViewController:readMeViewController animated:YES];
and whenever I need to look for my class overview just press ctrl+6 and below is the result

4. result (class overview) :

Cheers!! we will use it from now ..Happy Coding :)

Tuesday, May 22, 2012

iPhone Tips and Tricks

How to disable ARC in Xcode for Latest iOS Applications

1. Select Project --> Builds Phases -->Compile Sources

double click and File for which you want to disable ARC --> In pop window paste this command
That's it, Build project, Enjoy!!


How to get Current Device Info (like it is iPhone,iPad or iPhone Simulator etc.)

Just use the Below code and you will get return string as

NSString *deviceType = [[UIDevice currentDevice] model];
NSLog(@"My Current Device is : %@",deviceType);

iPhone Device Name = " iPhone "
iPhone Simulator Name = " iPhone Simulator "
iPad Simulator Name = " iPad Simulator "
iPod Device Name = " iPod touch " 


Show/Hide Hidden Files on Your Mac

1. Show Hidden files
1.1 Launch the Terminal (you can find Terminal this way)

      Go --> Utilities - > Terminal

1.2  paste this command

defaults write AppleShowAllFiles TRUE

1.3 Hit Enter
1.4 now for restart Finder hit below command

killall Finder

2. Hide Hidden files
1.1 Launch the Terminal (you can find Terminal this way)

      Go --> Utilities - > Terminal

1.2  paste this command

defaults write AppleShowAllFiles FALSE

1.3 Hit Enter
1.4 now for restart Finder hit below command

killall Finder

How to Create Button programatically

1. add below code in viewDidLoad method of ViewController

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"My Button" forState:UIControlStateNormal];
    button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
    [self.view addSubview:button];

2. add this method and Go for Execute the code for desired output.

-(void) buttonPressed{
    NSLog(@"My Button pressed.");


How to get Current Device Orientation (like It's Portrait or Landscape etc.)

Just use the Below code and you will get result

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
UIInterfaceOrientation orientationType = [UIDevice currentDevice].orientation;
    NSLog(@"Device's Current Orientation is : %d",orientationType);
    if(orientationType == 0){
        //this is really a just a failsafe.
        NSLog(@"Orientation is in :Default Portrait :");
    }else if(orientationType == 1){        
        NSLog(@"Orientation is in : Portrait :");
    }else if(orientationType == 2){        
        NSLog(@"Orientation is in : Portrait UpsideDown :");
    }else if(orientationType == 3){        
        NSLog(@"Orientation is in : Landscape Left :");
    }else if(orientationType == 4){        
        NSLog(@"Orientation is in : Landscape Right :");


How to change Navigation Bar's Background colour and Title programatically

add below code in viewDidLoad :
1. update tint color
//set Green Colour
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:34/255.0f green:139/255.0f blue:34/255.0f alpha:1];

2. add title
self.title = @"Welcome Screen";

How to add Bar-Button on Navigation Bar

1. Make sure you have already added Navigation Bar controller in application

2. Create UIBarButton

UIBarButtonItem *signIn_BarButton = [[UIBarButtonItem alloc]initWithTitle:@" SIGN IN " style:UIBarButtonItemStyleBordered target:self action:@selector(signInUser)];
UIColor *button_color = [UIColor colorWithRed:109.0/255.0 green:152.0/255.0 blue:136.0/255.0 alpha:1.0];
signIn_BarButton.tintColor =button_color;

3. Add it to Navigation Bar Controller (on right side)

self.navigationItem.rightBarButtonItem =signIn_BarButton;

4. Add the method for Button click

-(void) signInUser{
    signInViewController = [[SignInViewController alloc] init];
    [self.navigationController pushViewController:signInViewController animated:YES];

5. here is the result screen


Handle Screen Orientations in iOS 5 and iOS 6 

//For up-to iOS 5.0
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    // Return YES for supported all orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);

//For iOS 6.0
    //Supporting only portrait orientation.
    return UIInterfaceOrientationMaskPortrait;

    return NO;


How to disable NSLog in Xcode for Production stage

Add #define NSLog  in appName-Prefix.pch file in Supporting Files Folder of your project
and result file code look like..

// Prefix header for all source files of the 'NSLog' target in the 'NSLog' project

#import <Availability.h>

#ifndef __IPHONE_4_0
#warning "This project uses features only available in iOS SDK 4.0 and later."

#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>

//Add this to disable NSLog
#define NSLog


How to Get Current Device Width and Hieght

    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    CGFloat screenHeight = screenRect.size.height;