Archive for August, 2011

Some Q’s With Answers


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?

XYZAppDelegate *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];

Leave a comment

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];
}

Leave a comment

Adding Right Bar Button Item


UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@”Done” style:UIBarButtonItemStyleBordered target:self action:@selector(done)];

self.navigationItem.rightBarButtonItem = rightBarButtonItem;

[rightBarButtonItem release];

Leave a comment

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];
}
}

Leave a comment

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

Leave a comment

NSDate


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];

Leave a comment

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”];

Leave a comment

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.

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];

Leave a comment

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 } }

Leave a comment

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&#8221;;
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];
}

Leave a comment