Thursday, June 28, 2012

Add two pickerviews programmatically.

Two UIPickerView together in one ViewController Programatically.

We will add two pickerviews programmatically.
Goal: we want to add two pickerviews in one viewcontroller. By pressing on a button will display a pickerview and when we will select from any of the pickerview its selected row will be displayed on button. When one button is pressed if other pickerview is on screen we will remove it. Also if user touches on any other part of the screen, both pickerviews will hide and removed.
Are your ready to Start?
Open the Xcode, From the file menu select New Project. Name the project PickerViewExample. Now add another view controller from Class->New->add File now select UIViewControllerSubClass. Check with Xib option and leave other as uncheck. HomeViewController is the class where we will create our two pickerviews.
Now open the HomeViewController.h and write following code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#import
 
@interface HomeViewController : UIViewController
< UIPickerViewDataSource,UIPickerViewDelegate> {
    UIPickerView *countryTypePicker;
    UIPickerView *categoryTypePicker;
    NSArray *countryTypes;
    NSArray *categoryTypes;
    IBOutlet UIButton *countryTypeBtn;
    IBOutlet UIButton *categoryTypeBtn;
      NSArray *pickersArray;
    UIPickerView *activePickerView;
}
@property (nonatomic,retain)     UIPickerView *activePickerView;
-(IBAction) showCountryTypePicker;
-(IBAction) showCategoryTypePicker;
@end

Open the HomeViewController Nib and add two buttons. One button will contain selected country and one will contain select category.Assign tag 0 and 1 to both these buttons. Also there are two function attached with buttons showCountryTypePicker and ShowCategoryTypePicker.
Now under first line of HomeViewController add following lines
#define kPICKERCOLUMN 1
#define kCATEGORYTYPEPICKERTAG 20
#define kCUISINETYPEPICKERTAG 21
first line shows number of columns in each picker while second and third line are unique tags that we will assign to each picker.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
        categoryTypes = [[NSArray alloc] initWithObjects:@"Appetizers",@"Breakfast",@"Dessert",@"Drinks",
                         @"Main Dish/Entree", @"Salad", @"Side Dish", @"Soup", @"Snack",
                         @"Baby Food", @"Pet Food",nil]; 
 
        countryTypes = [[NSArray alloc] initWithObjects:@"African",@"American",@"Armenian",@"Barbecue",
                         @"Brazilian", @"British", @"Cajun", @"Central American", @"Chicken",
                         @"Chinese", @"Cuban",
                         @"Ethiopian", @"French", @"Greek", @"German", @"Hamburgers",
                         @"Homestyle Cooking", @"Indian", @"Irish", @"Italian", @"Jamaican",
                         @"Japanese", @"Korean", @"Mexican", @"Middle Eastern", @"Pakistani",
                         @"Pancakes /Waffles", @"Persian", @"Pizza", @"Polynesian", @"Russian",
                         @"Sandwiches", @"Seafood", @"Scandinavian", @"Spanish", @"Soul Food",
                         @"South American", @"Steak", @"Vegetarian", @"Tex-Mex", @"Thai",
                         @"Vietnamese",@"Wild Game",nil];
    }
    return self;
}
These are two arrays that we will bind with two pickers.
Now uncomment the viewDidLoad method and replace with following
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (void)viewDidLoad {
    [super viewDidLoad];
    categoryTypePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0,250,400,160)];
    categoryTypePicker.tag = kCATEGORYTYPEPICKERTAG;
    categoryTypePicker.showsSelectionIndicator = TRUE;
    categoryTypePicker.dataSource = self;
    categoryTypePicker.delegate = self;
    categoryTypePicker.hidden = YES;
    countryTypePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0,250,400,160)];
    countryTypePicker.backgroundColor = [UIColor blueColor];
    countryTypePicker.tag = kCUISINETYPEPICKERTAG;
    countryTypePicker.showsSelectionIndicator = TRUE;
    countryTypePicker.hidden = YES;
    countryTypePicker.dataSource = self;
    countryTypePicker.delegate = self;
pickersArray =  [[NSArray alloc] initWithObjects: categoryTypePicker, countryTypePicker ,nil];//add your both pickers to this array and we will use button tags to get picker from this array and alternate between two pickers
}
Initially both pickers will be hidden. We assigned different tag to each picker.
If we want to hide the pickerview if touched outside the button add your code to following method
1
2
3
4
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)eve
{
 
}
1
2
3
4
5
6
#pragma mark -
#pragma mark picker methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return kPICKERCOLUMN;
}
This method tells how many columns in each picker. We want one column in each picker.
1
2
3
4
5
6
7
8
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView.tag == kCATEGORYTYPEPICKERTAG)
        return [categoryTypes count];
    else
        return [countryTypes count];
 
}
This method will tell how many rows in each picker based on tag it binds the relevant array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView.tag == kCATEGORYTYPEPICKERTAG)
        return [categoryTypes objectAtIndex:row];
    else
        return [countryTypes objectAtIndex:row];
 
} //this mehtod shows title for each row in picker
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (pickerView.tag == kCATEGORYTYPEPICKERTAG) {
        NSString *categoryType  = [categoryTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
        [categoryTypeBtn setTitle:categoryType forState:UIControlStateNormal]; 
 
    }else {
 
        NSString *countryType  = [countryTypes objectAtIndex:[pickerView selectedRowInComponent:0]];
        [countryTypeBtn setTitle:countryType forState:UIControlStateNormal];               
 
    }  
 
} //this method displays whenever selection indicator stops the row title is set as button title.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Thanks to Nick Staresinic for pointing out this bug..
//call this function on both button clicks
-(IBAction) alternatePickers: (id) sender{ 
 
        UIButton * control = (UIButton*) sender;
        if (self.activePickerView) {
 
            [self.activePickerView removeFromSuperview];
 
        }
        NSLog(@"Segment index:%d",control.tag);
        self.activePickerView = [pickersArray objectAtIndex:control.tag];
 
        [self.view  addSubview:self.activePickerView];
 
}
In above method if one of the button is pressed we hide other picker and remove it from view if it there. From Interface builder please connect this method with each button on Touchupinside event.
Now comes the memory management part. Replace your dealloc with follow method.
1
2
3
4
5
6
7
- (void)dealloc {
    [countryTypes release];
    [categoryTypes release];
    [categoryTypePicker release];
    [countryTypePicker release];;
    [super dealloc];
}
We have done most of our work now we will add our HomeViewController to main window. Open the PickerViewExampleAppDelegate.h above the implementation tag add @class HomeViewController. add following line
HomeViewController *homeViewController;
Now open PickerViewExampleAppDelegate.m and add HomeViewController.h. Now replace your following function with this
1
2
3
4
5
6
7
8
9
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {   
 
    // Override point for customization after application launch.
    homeViewController = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
    [window addSubview:homeViewController.view];
    [self.window makeKeyAndVisible];
 
    return YES;
}
In its dealloc you will release [homeViewController release];


New iPhone Interview Questions 2

Difference between shallow copy and deep copy?

Ans: Shallow copy is also known as address copy. In this process you only copy address not actual data while in deep copy you copy data.
Suppose there are two objects A and B. A is pointing to a different array while B is pointing to different array. Now what I will do is following to do shallow copy.
Char *A = {‘a’,’b’,’c’};
Char *B = {‘x’,’y’,’z’};
B = A;
Now B is pointing is at same location where A pointer is pointing.Both A and B in this case sharing same data. if change is made both will get altered value of data.Advantage is that coping process is very fast and is independent of size of array.
while in deep copy data is also copied. This process is slow but Both A and B have their own copies and changes made to any copy, other will copy will not be affected.
What is advantage of categories? What is difference between implementing a category and inheritance? 

Ans: You can add method to existing class even to that class whose source is not available to you. You can extend functionality of a class without subclassing. You can split implementation in multiple classes. While in Inheritance you subclass from parent class and extend its functionality.
Difference between categories and extensions?

Ans:Class extensions are similar to categories. The main difference is that with an extension, the compiler will expect you to implement the methods within your main @implementation, whereas with a category you have a separate @implementation block. So you should pretty much only use an extension at the top of your main .m file (the only place you should care about ivars, incidentally) — it’s meant to be just that, an extension.
Difference between protocol in objective c and interfaces in java?

Ans:Protocol is also way to relate classes that are not related in inheritance hierarchy. Protocols and interfaces both are used to achieve multiple inheritance.
There is minor difference between these two. In Objective-C, protocols also implement NSObject protocol to access all the mehthods in NSObject
@protocol WebProtocol <NSObject>
@end
If I don’t implement NSObject explicitly, I will not be able to access NSObject methods like retain, release etc. when I access through WebProtocol instance.
While in Java you don’t need to implement Object interface explicitly. It is implicitly implemented.
This link will help you. Thanks to Tom Jefferys.
http://stackoverflow.com/questions/990360/differences-between-java-interfaces-and-objective-c-protocols
What are KVO and KVC?
KVC: Normally instance variables are accessed through properties or accessors but KVC gives another way to access variables in form of strings. In this way your class acts like a dictionary and your property name for example “age” becomes key and value that property holds becomes value for that key. For example, you have employee class with name property.
You access property like
NSString age = emp.age;
setting property value.
emp.age = @”20″;
Now how KVC works is like this
[emp valueForKey:@"age"];
[emp setValue:@"25" forKey:@"age"];
KVO : The mechanism through which objects are notified when there is change in any of property is called KVO.
For example, person object is interested in getting notification when accountBalance property is changed in BankAccount object.To achieve this, Person Object must register as an observer of the BankAccount’s accountBalance property by sending an addObserver:forKeyPath:options:context: message.
Can we use two tableview controllers on one view controller?

Ans: Yes, we can use two tableviews on the same view controllers and you can differentiate between two by assigning them tags…or you can also check them by comparing their memory addresses.
What is keyword atomic in Objective C?

Ans: When you place keyword atomic with a property, it means at one time only one thread can access it.

What are mutable and immutable types in Objective C?

Ans: Mutable means you can change its contents later but when you mark any object immutable, it means once they are initialized, their values cannot be changed. For example, NSArray, NSString values cannot be changed after initialized.
When we call objective c is runtime language what does it mean?
Ans: Objective-C runtime is runtime library that is open source that you can download and understand how it works. This library is written in C and adds object-oriented capabilities to C and makes it objective-c. It is only because of objective c runtime that it is legal to send messages to objects to which they don’t know how to respond to. Methods are not bound to implementation until runtime. Objective-C defers its decisions from compile time to run time as much as it can. For example, at runtime, it can decide to which object it will send message or function.
What is difference between NSNotification and delegate?
Ans:Delegate is passing message from one object to other object. It is like one to one communication while nsnotification is like passing message to multiple objects at the same time. All other objects that have subscribed to that notification or acting observers to that notification can or can’t respond to that event. Notifications are easier but you can get into trouble by using those like bad architecture. Delegates are more frequently used and are used with help of protocols.
Swap the two variable values without taking third variable?

Ans:-
int x=10;
int y=5;
x=x+y;
NSLog(@”x==> %d”,x);
y=x-y;
NSLog(@”Y Value==> %d”,y);
x=x-y;
NSLog(@”x Value==> %d”,x);
Thanks to Subrat for answering this question.
What is push notification?
Imagine, you are looking for a job. You go to software company daily and ask sir “is there any job for me” and they keep on saying no.  Your time and money is wasted on each trip.(Pull Request mechanism)
So, one day owner says, if there is any suitable job for you, I will let you know. In this mechanism, your time and money is not wasted. (Push Mechanism)
How it works?
This service is provided by Apple in which rather than pinging server after specific interval for data which is also called pull mechanism, server will send notification to your device that there is new piece of information for you. Request is initiated by server not the device or client.
Flow of push notification
Your web server sends message (device token + payload) to Apple push notification service (APNS) , then APNS routes this message to device whose device token specified in notification.
What is polymorphism?
This is very famous question and every interviewer asks this. Few people say polymorphism means multiple forms and they start giving example of draw function which is right to some extent but interviewer is looking for more detailed answer.
Ability of base class pointer to call function from derived class at runtime is called polymorphism.
For example, there is super class human and there are two subclasses software engineer and hardware engineer. Now super class human can hold reference to any of subclass because software engineer is kind of human. Suppose there is speak function in super class and every subclass has also speak function. So at runtime, super class reference is pointing to whatever subclass, speak function will be called of that class. I hope I am able to make you understand.
What is responder chain?
Ans: Suppose you have a hierarchy of views such like  there is superview A which have subview B and B has a subview C. Now you touch on inner most view C. The system will send touch event to subview C for handling this event. If C View does not want to handle this event, this event will be passed to its superview B (next responder). If B also does not want to handle this touch event it will pass on to superview A. All the view which can respond to touch events are called responder chain. A view can also pass its events to uiviewcontroller. If view controller also does not want to respond to touch event, it is passed to application object which discards this event.
Apple responder chain
Apple responder chain


ThankQ

Praveen