Search This Blog

Wednesday, September 15, 2010

UIImagePickerController


- (void)takePicture:(id)sender
{
NSString *deviceType = [UIDevice currentDevice].model;
if( ![deviceType isEqualToString:@"iPhone"] )
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentModalViewController:imagePicker animated:YES];
[imagePicker release];
}
else
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentModalViewController:imagePicker animated:YES];
[imagePicker release];
}
}


UIKit FrameWork

UIWebView
-(void)viewDidLoad
{

CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);

UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];
[webView setBackgroundColor:[UIColor whiteColor]];
[webView setDelegate:self];
NSString *urlAddress = @"http://www.google.com";
NSURL *url = [NSURL URLWithString:urlAddress];
*requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
[self addSubview:webView];
[webView release];
}

//Web View delegate methods
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{

}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
//started loading
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//Finished loading
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
//Error in loading
}



UItextField


-(void)viewDidLoad
{

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 30, 150, 40)];
NSLog(@"LOAD");
[textField setBorderStyle:UITextBorderStyleRoundedRect];
[textField setFont:[UIFont systemFontOfSize:28]];
[textField setTextColor:[UIColor redColor]];
[textField setBackgroundColor:[UIColor yellowColor]];
[textField setAdjustsFontSizeToFitWidth:YES];
[textField setClearButtonMode:UITextFieldViewModeWhileEditing];
[textField setReturnKeyType:UIReturnKeyDone];
[textField setKeyboardAppearance:UIKeyboardAppearanceAlert];
//[textField setDelegate:self];
//[textField setText:@"SAMPLE"];
[self.view addSubview:textField];
//[textField becomeFirstResponder];
[textField release];

}
Text field Delegate Methods



- (void)textFieldDidBeginEditing:(UITextField *)textField
{
NSLog(@"BEGIN = %@", [textField text]);

}

- (void)textChanged:(NSNotification *)aNotification
{
NSLog(@"TEXT CHANGED = %@", [aNotification userInfo]);
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{
NSLog(@"CHAR = %@", [textField text]);
return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSLog(@"RETURN = %@", [textField text]);
[textField resignFirstResponder];
return YES;
}




UISwitch


-(void)viewDidLoad
{

UISwitch *aSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(100, 290, 300, 100)];
[self.view addSubview:aSwitch];
[aSwitch release];
[aSwitch setOn:YES];
[aSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
}


- (void)switchAction:(UISwitch *)aSwitch
{
NSLog(@"SWITCH = %d", [aSwitch isOn]);
}


UISlider

-(void)viewDidLoad
{

UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(20, 320, 100, 100)];
[self.view addSubview:slider];
[slider release];
[slider setMaximumValue:100.0f];
[slider setMinimumValue:1.0f];
[slider setValue:50.0f];
[slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
}

- (void)sliderAction:(id)slider
{
NSLog(@"SLIDER = %f", [(UISlider *)slider value]);
}



UIImageView

-(void)viewDidLoad
{

UIImageView *anImageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 280, 200, 200)];
//[anImageView setImage:anImage];
[anImageView setImage:[UIImage imageNamed:@"CAMPUS TOUR BLACK.png"]];

[self.view addSubview:anImageView];
[anImageView setBackgroundColor:[UIColor purpleColor]];
[anImageView setContentMode:UIViewContentModeCenter];
[anImageView release];

NSArray *imagesArray = [NSArray arrayWithObjects:[UIImage imageNamed:@"Images/bg_circle.png"], [UIImage imageNamed:@"CAMPUS TOUR BLACK.png"], nil];
[anImageView setAnimationImages:imagesArray];
[anImageView setAnimationDuration:0.5f];
[anImageView setAnimationRepeatCount:1];
[anImageView startAnimating];
//[anImageView stopAnimating];
//[anImageView isAnimating];
}


UIActivityIndicatorView

UIActivityIndicatorView *anActivityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
CGRect indicatorFrame = [anActivityIndicator frame];
indicatorFrame.origin = CGPointMake(200, 100);
anActivityIndicator.frame = indicatorFrame;
[anActivityIndicator setHidesWhenStopped:YES];
[anActivityIndicator startAnimating];
//[anActivityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
[self.view addSubview:anActivityIndicator];
[anActivityIndicator release];



UIProgressView
-(void)viewDidLoad
{
UIProgressView *progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
[self.view addSubview:progressView];
[progressView setTag:100];
[progressView setCenter:CGPointMake(200, 180)];
[progressView setProgress:0.5];
[progressView release];

[NSTimer scheduledTimerWithTimeInterval:0.5f target:self selector:@selector(progressBarChange:) userInfo:[NSMutableDictionary dictionaryWithObject:[NSNumber numberWithFloat:0] forKey:@"ProgressValue"] repeats:YES];
}

- (void)progressBarChange:(NSTimer *)aTimer
{
NSMutableDictionary *userInfo = [aTimer userInfo];
float progressValue = [[userInfo objectForKey:@"ProgressValue"] floatValue];
[(UIProgressView *)[self.view viewWithTag:100] setProgress:progressValue];
progressValue += 0.1;
if( progressValue > 1.1f)
{
[aTimer invalidate];
}

[userInfo setObject:[NSNumber numberWithFloat:progressValue] forKey:@"ProgressValue"];

}



UILabel

-(void)viewDidLoad
{

UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 80, 150, 100)];
[aLabel setText:@"Sample Label asdasd asd as da "];
[aLabel setNumberOfLines:0];
[aLabel setBackgroundColor:[UIColor redColor]];
[aLabel setTextAlignment:UITextAlignmentRight];
[self.view addSubview:aLabel];
[aLabel release];
}


UIButton

-(void)viewDidLoad
{

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[aButton setTitle:@"BUTTON" forState:UIControlStateNormal];
[aButton setFrame:CGRectMake(20, 180, 150, 100)];
[self.view addSubview:aButton];
[aButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchDown];
UIImage *anImage = [[UIImage alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/Images/bg_circle.png", [[NSBundle mainBundle] resourcePath]]];

//[aButton setImage:[UIImage imageNamed:@"Images/bg_circle.png"] forState:UIControlStateNormal];
[aButton setImage:anImage forState:UIControlStateNormal];
[anImage release];
}

- (void)buttonAction:(UIButton *)aButton
{
NSLog(@"BUTTON = %@", aButton);
[aButton setTitle:@"CLICKED" forState:UIControlStateNormal];
}





NSThread


1. Create the new thread:
[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];
2. Create the method that is called by the new thread:

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

What if you need to do something to the main thread from inside your new thread (for example, show a loading symbol)? Use performSelectorOnMainThread.

[self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:false];

NSTimer

Timers

This timer will call myMethod every 1 second.

[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(myMethod) userInfo:nil repeats:YES];

What if you need to pass an object to myMethod? Use the "userInfo" property.
1. First create the Timer
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(myMethod) userInfo:myObject repeats:YES];

2. Then pass the NSTimer object to your method:
-(void)myMethod:(NSTimer*)timer
{
// Now I can access all the properties and methods of myObject [[timer userInfo]myObjectMethod];
}

To stop a timer, use "invalidate":
[myTimer invalidate];
myTimer = nil; // ensures we never invalidate an already invalid Timer

Basic Concepts in iPhone SDK

NSString and int

currentScoreLabel.text = [NSString stringWithFormat:@"%d", currentScore];

Vibration and Sound

Here is how to make the phone vibrate (Note: Vibration does not work in the Simulator, it only works on the device.)
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

Sound will work in the Simulator, however some sound (such as looped) has been reported as not working in Simulator or even altogether depending on the audio format. Note there are specific filetypes that must be used (.wav in this example).
SystemSoundID pmph; id sndpath = [[NSBundle mainBundle] pathForResource:@"mySound" ofType:@"wav" inDirectory:@"/"]; CFURLRef baseURL = (CFURLRef) [[NSURL alloc] initFileURLWithPath:sndpath]; AudioServicesCreateSystemSoundID (baseURL, &pmph); AudioServicesPlaySystemSound(pmph); [baseURL release];


Random Numbers

Use arc4random(). There is also random(), but you must seed it manually, so arc4random() is preferred.

Time

Calculate the passage of time by using CFAbsoluteTimeGetCurrent().
CFAbsoluteTime myCurrentTime = CFAbsoluteTimeGetCurrent(); // perform calculations here

Alerts

Show a simple alert with OK button.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"An Alert!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release];


Plist files

Application-specific plist files can be stored in the Resources folder of the app bundle. When the app first launches, it should check if there is an existing plist in the user's Documents folder, and if not it should copy the plist from the app bundle.
// Look in Documents for an existing plist file

NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0]; myPlistPath = [documentsDirectory stringByAppendingPathComponent:

[NSString stringWithFormat: @"%@.plist", plistName] ];
[myPlistPath retain]; // If it's not there, copy it from the bundle

NSFileManager *fileManger = [NSFileManager defaultManager];

if ( ![fileManger fileExistsAtPath:myPlistPath] )
{
NSString *pathToSettingsInBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
}

Now read the plist file from Documents
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@"myApp.plist"];
NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];

Now read and set key/values
myKey = (int)[[plist valueForKey:@"myKey"] intValue];
myKey2 = (bool)[[plist valueForKey:@"myKey2"] boolValue];
[plist setValue:myKey forKey:@"myKey"];
[plist writeToFile:path atomically:YES];




Info button

Increase the touchable area on the Info button, so it's easier to press.
CGRect newInfoButtonRect = CGRectMake(infoButton.frame.origin.x-25, infoButton.frame.origin.y-25, infoButton.frame.size.width+50, infoButton.frame.size.height+50); [infoButton setFrame:newInfoButtonRect];


Detecting Subviews

You can loop through subviews of an existing view. This works especially well if you use the "tag" property on your views.
for (UIImageView *anImage in [self.view subviews]) { if (anImage.tag == 1) { // do something } }




Tuesday, September 14, 2010

Casting

All About Casting

A few days ago Christopher & I chatted with an iPhone in Action reader about why Listing 18.3 in the book generated the warning "Warning: 'UIView' may not respond to -addPic:at:'". The answer is casting, and I think it's a topic that deserves some additional discussion.

All About Casting

Casting is a fundamental of C. Wikipedia defines it as an "explicit type conversion." We demonstrate it briefly on p.156, where we show that you can turn a float into an int with a little bit of casting magic:

float a = 6.00;
int b;
b = (int) a;

Beyond that, we give it pretty short attention. That's probably great for folks with experience with rigorous programming languages, but less useful for those of you just getting into them for the first time.

So in this article I'm going to talk more about casting by concentrating on three three times that I've seen it most in SDK development (and thus where you're most likely to encounter it). In order I'm going to cover: toll-free bridging; math casts; and, finally, method casts (the topic that got us started).

Toll-Free Bridging

This is the other cast-related topic that we covered pretty extensively in iPhone in Action. There are some details on p.157 (at the end of the discussion of casting) and on p.321 (in the "Using Core Fondation" box).

Much of your iPhone programming will be done using Cocoa frameworks, such as the UI and NS libraries. However, sometimes you'll have to instead use Apple's older libraries, such as Core Foundation. Core Foundation is object-oriented, just like the NS libraries, and as a result you end up with alternative ways to represent a lot of standard variable types. For example Core Foundation's CFStringRef and Cocoa's NSString * are alternate ways to represent strings.

Fortunately, Apple recognizes this equivalence and "toll-free bridges" equivalent Core Foundation and NS classes. In order to use one in the place of another, you just need to cast it, as we do throughout Listing 16.11 (pp.318-320):

(NSString *)ABRecordCopyCompositeName(thisPerson);

This sort of casting will come up frequently if you use older frameworks, such as Address Book and Core Graphics.

Math Casting

I've run into the most problem with casting when I was writing mathematical formulas. Listing 17.10 (pp.340-341) shows off one such examples. Most of the way through that example, you can see a line which reads:

int currentHeight = 395 - ceil((float)newLocation.altitude/savedDestinationHeight*(401-65));

Clearly, that's a cast, but I don't really explain why in the description of the code.

I had to cast because of the "int" variable that I'm saving the formula off to. A problem arises because there's not necessarily a consensus (among all programming languages) for how to treat the right-hand side of such an equation. Should the elements all be treated as integers, or should they be left in their native form until the final conversion is done? Apple's Objective-C appears to assume a conversion to the final variable type almost immediately.

In this situation that resulted in altitude/height being made into an integer before it was multiplied by 401-65, which was not the desired result, because I was trying to generate a percent (meaning that 0 or 1 was really not useful). Thus the cast of that division as a float.

I find this sort of thing to be the one situation where a cast is really required ... where leaving it out results in your program not working, and it can be very confusing to figure out why.

Method Casting

And so finally we come to query that started this article off. If you compile the code associated with Listing 18.3, you'll see "Warning: 'UIView' may not respond to -addPic:at:'". This is a non-fatal warning that has to do with yet another casting nuisance. You'll find the line that generates the warning at the top of p.353:

[self.view addPic:myImageView.image at:myImageView.frame];

If you think about it, the reason for this warning should jump out. The view controller's view property is defined as a UIView, which does not contain the addPic:at: method introduced in CollageView. Thus, if you don't like the warning, you can just cast the property appropriately:

[(collageView *)self.view addPic:myImageView.image at:myImageView.frame];

You can run into this sort of thing when a property or method assumes a very specific class of object, rather than the more general "id." If memory serves I also hit it when using the nextResponder method (probably in Listing 14.2 on p.247).

Some Final Words on Casting Warnings

It's important to note that casting problems will generally result in warnings.You don't have to resolve them. In particular a warning about uncasted toll-free bridging or a warning about an uncasted method isn't a problem as long as you know what you're doing. It's usually worth fixing them, just to make sure that you understand the reason for the warning, but you don't have to if you're doing something quick-and-dirty or have some reason to leave the warning in.

(In the case of the warning generated by Listing 18.3 we opted to leave out the casting to keep the code more readable, not really thinking about the fact that people might be concerned about the warning if they compiled the code.)

Much more insidious are the math-related casting problems which probably won't generate a warning at all. In my opinion, they're what you really have to watch out for--and they're also a good reason to generally be conscientious about casting all the time, so that you don't run into mystery problems without warnings when you get careless about math casts.

Common SDK Errors

Problems: My UIImage Doesn't Display on a Device!

One of the more frustrating problems that you can run into when developing for the iPhone is having everything work great on the simulator, but then fail when you load it onto a real device. One of the more common problems that shows up is when a UIImage that displayed on the simulator is missing on the iPhone.

Some folks trying to use the SplashScreen library have had this precise problem.

The problem is usually one of case. Your Macintosh is (probably) built on a case-independent file system. That means that if you try to load "Splash.png" when the filename is really "splash.png", it'll work fine.

Your iPhone is not case-independent, and thus it will fail to find the same file.

So, if you're unable to see a picture on an actual device, check the case of your file name first.

Monday, September 13, 2010

Touches Functions



- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch *touch = [touches anyObject];
CGPoint pnt = [touch locationInView:self.view];
}


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint pnt = [touch locationInView:self.view];

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint pnt = [touch locationInView:self.view];
}

UIScrollView

UIScrollView Image Gallery Tutorial

Using a UIScrollView to create a paging application seems to be a question I am frequently asked about. I decided to create this tutorial to show how you can create an image gallery with a UIScrollView. I will show you have to reuse two UIImageViews views to avoid creating a UIImageView for each image in the gallery. Full tutorial and source after the jump.

how to lift view up when keyboard is pressed?

- (void) animateTextField: (UITextView*)textField up:(BOOL) up
{
const int movementDistance = 300;
const float movementDuration = 0.4f;

int movement = (up ? -movementDistance : movementDistance);

[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.view.frame = CGRectOffset(self.view.frame, 0, movement);
[UIView commitAnimations];
}

//in text field didbegin editing method call above one
- (void)textViewDidBeginEditing:(UITextView *)textField
{
if (txtField.frame.origin.y > 150)
[self animateTextField:textField up: YES];
}
//and when ever user pressed done button on keyboard for view to come down write below method

- (void)textViewDidEndEditing:(UITextView *)textField
{
if (txtField.frame.origin.y > 150)
[self animateTextField:textField up: NO];
}


NSUserDefaults


Saving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];
// saving an NSInteger
[prefs setInteger:42 forKey:@"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:@"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:@"floatKey"];
// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];
Retrieving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:@"integerKey"];
// getting an Float
float myFloat = [prefs floatForKey:@"floatKey"];


NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
@"", kDefaultsUsernameKey,
@"", kDefaultsPasswordKey,
nil];

[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
[[NSUserDefaults standardUserDefaults] synchronize];

NSSet and NSMutableSet

//NSSet
NSSet *aSet = [NSSet alloc]initWithObjects
NSSet *aSet = [NSSet setWithObjects:@"one",@"two",@"three",nil];
[aSet initWithObjects:@"",@"",nil];
[aSet initWithSet:set2];
[aSet initWithArray:array];

//Count of an Set
[aSet count];

//Operations in Set
1.Intersection
[aSet intersectsSet:set2];
2.Union
[aSet unionSet:set2];
3.Remove Objects
[aSet removeObjects];
4.Minus
[aSet minusSet:set2];


//Adding Objects to the Set
NSMutableSet *mSet = [NSMutableSet setWithObjects:@"",nil];

[mSet setByAddingObject:@"Kumar"];
[mSet setByAddingObjectsFromSet:set2];
[mSet setByAddingObjectsFromArray:array];

NSDate

NSDate *currentDate = [NSDate date];
//To print Current date
NSLog(@"the date is %@",currentDate); //it displays with time

//How to add time to Date
[NSDate dateWithTimeIntervalSinceNow:60*60]; //It will add 1 hour to the present time

//How to manually give the Dates
[NSDate dateWithStrin]

//How to compare Dates
if([currentDate isEqualToDate:date2])

//print Description
[currentDate description];

NSNumber and NSDecimal Number

//NSNumber and NSDecimalNumber
NSNumber *aNumber = [NSNumber numberWithInt:21];
NSNumber *aNumber = [NSNumber numberWithChar:'c'];
NSNumber *aNumber = [NSNumber numberWithBool:YES:];
NSNumber *aNumber = [NSNumber numberWithFloat:3.2:];

//How to print an number
NSLog(@"the number is %@",aNumber); //Done use %d because aNumber is an type Object

//How to convert aNumber to an Integer value
int x = [aNumber intValue];
float x = [aNumber floatValue];
BOOL x = [aNumber boolValue];

//How to add NSNumber value to the Array
NSArray *arr = [NSArray arrayWithObject:aNumber];

NSArray *arr = [NSArray arrayWithObject:x]; //wrong bcz x is an primitive data type


//NSDecimalNumber
//Mainly this class used for storing the decimal values
NSDecimalNumber *dNumber = [[NSDecimalNumber alloc]initWithString:@"23.3"];

NSDictionary

Objective-C Dictionary Object classes allow data to be stored and managed in the form of key-value pairs where both the key and the value are objects.

Contents


• 1 What are Dictionary Objects?

• 2 Creating Dictionary Objects

• 3 Initializing and Adding Entries to a Dictionary Object

• 4 Getting an Entry Count

• 5 Accessing Dictionary Entries

• 6 Removing Entries from a Dictionary Object












What are Dictionary Objects?

In the previous chapter we looked at using array objects to store collections of objects. Dictionary objects fulfill a similar purpose except each object stored in the dictionary has associated with it a unique key (to be precise, the key is unique to the particular dictionary object). The unique key can be of any object type though to be useful they are typically string objects.

Objective-C dictionary objects are created using the NSDictionary and NSMutableDictionary classes. NSDictionary based objects are immutable (in other words once they have been created and initialized their contents cannot be modified). Mutable dictionaries are instantiated from the NSMutableDictionary class and may be modified after creation and initialization.

Creating Dictionary Objects

An empty, immutable dictionary object may be created as follows:

NSDictionary *bookListing = [NSDictionary dictionary];

Similarly, an empty mutable dictionary may be created as follows:

NSMutableDictionary *bookListing = [NSMutableDictionary dictionary];



Initializing and Adding Entries to a Dictionary Object

Each key-value pair contained within a dictionary is referred to as an entry. Once a relationship between a key and a value has been estabilshed that relationship cannot subsequently be modified.

New entries are added to a dictionary using the setObject instance method. This method takes as its arguments an object and a corresponding key:

NSMutableDictionary *bookListing = [NSMutableDictionary dictionary];


[bookListing setObject: @"Wind in the Willows" forKey: @"100-432112"];

[bookListing setObject: @"Tale of Two Cities " forKey: @"200-532874"];

[bookListing setObject: @"Sense and Sensibility" forKey: @"202-546549"];

[bookListing setObject: @"Shutter Island" forKey: @"104-109834"];

In the above example, the bookListing dictionary is initialized with four book names with corresponding reference codes to act as keys.

It is also possible to create and initialize a dictionary with a number of key-value pairs using the dictionaryWithObjectsAndKeys class method. For example, an alternative to the above code is as follows:

NSDictionary *bookListing = [NSDictionary dictionaryWithObjectsAndKeys: @"Wind in the Willows", @"100-432112", @"Tale of Two Cities ", @"200-532874", @"Sense and Sensibility", @"202-546549", @"Shutter Island", @"104-109834", nil];

Dictionaries may also be initialized using keys and values contained in arrays using the arrayWithObjects method:

NSArray *objectsArray = [NSArray arrayWithObjects: @"Wind in the Willows", @"Tale of Two Cities ", @"Sense and Sensibility", @"Shutter Island", nil];

NSArray *keysArray = [NSArray arrayWithObjects: @"100-432112", @"200-532874", @"202-546549", @"104-109834", nil];


NSDictionary *bookListing = [[NSDictionary alloc] initWithObjects: objectsArray forKeys: keysArray];



Getting an Entry Count

A count of the number of entries in a dictionary can be obtained using the count instance methods:

NSMutableDictionary *bookListing = [NSMutableDictionary dictionary];


int count;


[bookListing setObject: @"Wind in the Willows" forKey: @"100-432112"];

[bookListing setObject: @"Tale of Two Cities " forKey: @"200-532874"];

[bookListing setObject: @"Sense and Sensibility" forKey: @"202-546549"];

[bookListing setObject: @"Shutter Island" forKey: @"104-109834"];


NSLog (@"Number of books in dictionary = %i", [bookListing count]);



Accessing Dictionary Entries

Dictionary entries are accessed by referencing the key corresponding to the required entry via the objectForKey method. For example:

NSLog ( @"100-432112 = %@", [bookListing objectForKey: @"100-432112"]);

NSLog ( @"200-532874 = %@", [bookListing objectForKey: @"200-532874"]);

NSLog ( @"202-546549 = %@", [bookListing objectForKey: @"202-546549"]);

NSLog ( @"104-109834 = %@", [bookListing objectForKey: @"104-109834"]);

When combined with the previous code and executed, we would expect to see the following output:

100-432112 = Wind in the Willows

200-532874 = Tale of Two Cities

202-546549 = Sense and Sensibility

104-109834 = Shutter Island




Removing Entries from a Dictionary Object

Specific dictionary entries may be removed by referencing the key as an argument to the removeObjectForKey method. For example, to remove the book entry for "Shutter Island" we would write the following code:

[bookListing removeObjectForKey: @"104-109834"];

All entries in a dictionary may be removed using the removeAllObjects instance method:

[bookListing removeAllObjects];

NSArray

//NSArray

//How to create an array and initialize it
NSArray *array = [[NSArray alloc]init];
(or)
NSArray *array = [[NSArray alloc]initWithObjects:@"one",@"two",@"three",nil]; //Here Array is initialized with three String Elements
(or)
NSArray *array2 = [[NSArray alloc]initWithArray:array]; //Here array2 is initialized with the same three elements
(or)
NSArray *array = [[NSArray alloc]initWithContentsOfFile:path]; //Give the path and it will get the Elements

//w/o alloc and init methods
NSArray *array = [NSArray arrayWithObjects:@"one",@"two",@"three",nil];
NSArray *array = [NSArray arrayWithArray:array2];


//If u need only single element in a array
NSArray *array = [NSArray arrayWithObject:@"one"];

//How to get the Count of an Array
int length = [array count];

//How to Add an Element to the array
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"one",nil];
[array insertObject:@"two" atIndex:1];
[array insertObject:@"three" atIndex:2];

//How to Delete an Element From the Array
[array removeObjectAtIndex:1];

//How to remove Lase Object
[array removeLastObject];


//How to search an element in the Array
if([array containsObject:@"two"])
{
//do this
}

//Displaying the Array Description
NSLog(@"The Array is %@",[array descriptionWithLocale:nil]);
NSLog(@"The Array is %@",[array description]);

//How to get the array element Index
[array indexOfObject:@"two"];

NSNotifications

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receivedExteriorColors:)
name:kRBReceivedExteriorColorList
object:nil];

//How to post notification

[[NSNotificationCenter defaultCenter] postNotificationName:kRBFailedToReceiveReportValues
object:nil
userInfo:nil];


//how to remove notification

[[NSNotificationCenter defaultCenter] removeObserver:self name:kRBSuccessRequestFloorPlanFinance object:nil];

How to change switch names to Yes/No

[(UILabel *)[[[[[[switchRide subviews] lastObject] subviews] objectAtIndex:2] subviews] objectAtIndex:0] setText:@"Yes"];

Address Book in Iphone

-(IBAction)chooseContacts {
// creating the picker
if(!picker){
picker = [[ABPeoplePickerNavigationController alloc] init];
// place the delegate of the picker to the controll
picker.peoplePickerDelegate = self;
}
// showing the picker
[self presentModalViewController:picker animated:YES];
}

/************** Contacts Delegate Functions ***************/


- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSMutableArray *phones = [[NSMutableArray alloc] init];
int i;
for (i = 0; i < ABMultiValueGetCount(phoneMulti); i++) {
NSString *aPhone = [(NSString*)ABMultiValueCopyValueAtIndex(phoneMulti, i) autorelease];
// NSLog(@"PhoneLabel : %@ & Phone# : %@",aLabel,aPhone);
[phones addObject:aPhone];
}

NSString *mobileNo = [phones objectAtIndex:0];
phoneNo.text = mobileNo;
NSLog(mobileNo);
name.text = (NSString*)ABRecordCopyCompositeName(person);

ABMutableMultiValueRef emailMulti = ABRecordCopyValue(person, kABPersonEmailProperty);
NSMutableArray *emails = [[NSMutableArray alloc] init];
for (i = 0; i < ABMultiValueGetCount(emailMulti); i++) {
NSString *anEmail = [(NSString*)ABMultiValueCopyValueAtIndex(emailMulti, i) autorelease];
[emails addObject:anEmail];
}

if([emails count] > 0)
{
NSString *emailAdress = [emails objectAtIndex:0];

email.text = emailAdress;
NSLog(emailAdress);
}
[peoplePicker dismissModalViewControllerAnimated:YES];

return YES;
}

- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker
shouldContinueAfterSelectingPerson:(ABRecordRef)person
property:(ABPropertyID)property
identifier:(ABMultiValueIdentifier)identifier{


return NO;


}

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
// assigning control back to the main controller
[picker dismissModalViewControllerAnimated:YES];
}

call/sms/email


#pragma mark DialNumber
-(IBAction)callClicked
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",phoneNo.text]]];
}
#pragma mark SMSApplication
-(IBAction)smsClicked
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"sms:"]]];
}
#pragma mark EmailApplication
-(IBAction)emailClicked
{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"mailto:%@?subject=testMail&body=its test mail.",email.text]]];
}

Audio Player

- (void)viewDidLoad {
[super viewDidLoad];

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]];

NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
audioPlayer.delegate = self;

if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer play];

}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
if(successfully)
NSLog(@"Played successfully");
}
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player
{
NSLog(@"Interreption occured");
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player
{
NSLog(@"Interreption Ended");
}

pickerView creation

#pragma mark -
#pragma mark Picker View Methods

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {

return 2;
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {

return [arrayColors count];
}

- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {

return [arrayColors objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

if(component == 0)
NSLog(@"Selected Colors: %@ component :%i Index of selected color: %i", [arrayColors objectAtIndex:row],component, row);
else
NSLog(@"Selected Colors: %@ component :%i Index of selected color: %i", [arrayColors objectAtIndex:row],component, row);
}

Table View With indexing and all data source methods

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

if (searching)
return 1;
else
return [listOfItems count];
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

if (searching)
return [copyListOfItems count];
else {

//Number of rows it should expect should be based on the section
NSDictionary *dictionary = [listOfItems objectAtIndex:section];
NSArray *array = [dictionary objectForKey:@"Countries"];
return [array count];
}
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

if(searching)
return @"Search Results";

if(section == 0)
return @"Countries to visit";
else
return @"Countries visited";
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

if(searching)
return nil;

NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray addObject:@"1"];
[tempArray addObject:@"2"];
[tempArray addObject:@"3"];
[tempArray addObject:@"4"];
[tempArray addObject:@"5"];
[tempArray addObject:@"6"];
[tempArray addObject:@"7"];
[tempArray addObject:@"8"];
[tempArray addObject:@"9"];
[tempArray addObject:@"10"];
[tempArray addObject:@"11"];
[tempArray addObject:@"12"];
[tempArray addObject:@"13"];
[tempArray addObject:@"14"];
[tempArray addObject:@"15"];
[tempArray addObject:@"16"];
[tempArray addObject:@"17"];
[tempArray addObject:@"18"];
[tempArray addObject:@"19"];
[tempArray addObject:@"20"];
[tempArray addObject:@"21"];
[tempArray addObject:@"22"];
[tempArray addObject:@"23"];
[tempArray addObject:@"24"];
[tempArray addObject:@"25"];
[tempArray addObject:@"26"];

return tempArray;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {

if(searching)
return -1;

return index % 2;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if(cell == nil)
cell = [self getCellContentView:CellIdentifier];

UILabel *lblTemp1 = (UILabel *)[cell viewWithTag:1];
UILabel *lblTemp2 = (UILabel *)[cell viewWithTag:2];

if(searching) {

lblTemp1.text = [copyListOfItems objectAtIndex:indexPath.row];
lblTemp2.text = @"";
}
else {

//First get the dictionary object
NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:@"Countries"];
NSString *cellValue = [array objectAtIndex:indexPath.row];

lblTemp1.text = cellValue;
lblTemp2.text = @"Sub Value";
[cellValue release];
}

return cell;
}

- (UITableViewCell *) getCellContentView:(NSString *)cellIdentifier {

CGRect CellFrame = CGRectMake(0, 0, 300, 60);
CGRect Label1Frame = CGRectMake(10, 10, 290, 25);
CGRect Label2Frame = CGRectMake(10, 33, 290, 25);
UILabel *lblTemp;

UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CellFrame reuseIdentifier:cellIdentifier] autorelease];

//Initialize Label with tag 1.
lblTemp = [[UILabel alloc] initWithFrame:Label1Frame];
lblTemp.tag = 1;
[cell.contentView addSubview:lblTemp];
[lblTemp release];

//Initialize Label with tag 2.
lblTemp = [[UILabel alloc] initWithFrame:Label2Frame];
lblTemp.tag = 2;
lblTemp.font = [UIFont boldSystemFontOfSize:12];
lblTemp.textColor = [UIColor lightGrayColor];
[cell.contentView addSubview:lblTemp];
[lblTemp release];

return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

//Get the selected country

NSString *selectedCountry = nil;

if(searching)
selectedCountry = [copyListOfItems objectAtIndex:indexPath.row];
else {

NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:@"Countries"];
selectedCountry = [array objectAtIndex:indexPath.row];
}

//Initialize the detail view controller and display it.
DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:[NSBundle mainBundle]];
dvController.selectedCountry = selectedCountry;
[self.navigationController pushViewController:dvController animated:YES];
[dvController release];
dvController = nil;
}

- (NSIndexPath *)tableView :(UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {

if(letUserSelectRow)
return indexPath;
else
return nil;
}

- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {

//return UITableViewCellAccessoryDetailDisclosureButton;
//return UITableViewCellAccessoryDisclosureIndicator;
return UITableViewCellAccessoryNone;
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {

[self tableView:tableView didSelectRowAtIndexPath:indexPath];
}

Interview Questions

1. How Do u know the Model or device name?

NSString *deviceType = [UIDevice currentDevice].model;
if( ![deviceType isEqualToString:@"iPhone"] )
{
}


2.How to know the String is there in the Array?

NSString *str = @"Hello";
NSArray *array = [[NSArray arrayWithObjects:@"",@"",@"",nil];
[array containsObject:str];


3. How to create a File/Directory?

XYZ
AppDelegate *appDelegate = (XYZAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *documentsPath = [appDelegate applicationDocumentsDirectory];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *pathOfFile = [documentsPath stringByAppendingPathComponent:@"VehiclePics"];
if(![fileManager fileExistsAtPath: pathOfFile])
[fileManager createDirectoryAtPath:vehiclePicsPath attributes:nil];

4.How to convert CGImage to UIImage?
UIImage *anImage = [UIImage imageWithCGImage:imageMasked];

//Converting UIImage to CGImage
CGImage *img = [anImage CGIMage];


5.How to call Delegate File Methods?
[(
XYZAppDelegate *)[[UIApplication sharedApplication] delegate] stopLoadingView];


6.How to compare Action sheet Strings?
if([[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"Take Photo"])


7.What is that initWithNibName?
A: This method allows initializing a UIViewController’s view from a nib file rather than from
code. You use this method when you want to write code that initializes a view controller
whose view resides in a nib. You should note that this is just one of several different ways
you might load a view from a nib into a class. By book’s end, you will be familiar with
most of them.


8. What is a delegate?
A: A delegate is a way to simplify the separation of processing logic from another class.
It also avoids inheritance. For instance, subclassing the UIApplication object would
be painful. Instead, Apple provides a UIApplicationDelegate. The UIApplication has
a reference to the class implementing the UIApplicationDelegate. If implemented,
the UIApplication delegates handling an event to the appropriate method in the
UIApplicationDelegate. It appears as if UIApplication is handling the event; in reality,
its delegate, UIApplicationDelegate, handles the event. Delegates are a common
object-oriented design pattern. For more information on delegates and object-oriented
programming, refer to the “delegation pattern” on Wikipedia (www.wikipedia.org).

9.How do u know Application Name? And OS version and OS NAme?
Ans.
NSString *applicationName = [[NSProcessInfo processInfo] processName];


10.How to set backGround View For Table Views?

cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ListBg.png"]] autorelease];
cell.accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"disclosure.png"]] autorelease];

XML Parsing

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
attributes: (NSDictionary *)attributeDict
{
if([elementName isEqualToString:@"productName"])
{

}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if(soapResults)
[soapResults appendString: string];
}

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:@"productName"]){
productName = [[[NSString alloc] initWithString:soapResults] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

Web Services calling

calling web services

NSURLRequest *request1 = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://97.74.198.63:8080/psa-1.0/locateProduct.do?subCatId=661"]];
[[NSURLConnection alloc] initWithRequest:request1 delegate:self];



- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"Received Response");
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"Received Data");
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Connection Error");
// Show error
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Once this method is invoked, "responseData" contains the complete result
}

Table View Delegate Methods

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [listOfItems count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}

// Set up the cell...
NSString *cellValue = [listOfItems objectAtIndex:indexPath.row];
cell.text = cellValue;

return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//After selecting the row code should write here
}

iPhone Application Development Training

Hi Friends Iam N Radha Krishna.
I have done BTech in CSE and presently working as a iPhone and iPad Developer.I have done Apps on iPhone and published to App Store and even distributed apps through ADHOC Distribution also.Here We can find out code examples for the iPhone development.

Thanks
Radha Krishna