Using Pointers
//Using POINTER
int a = 10; //1. we set a = 10
int b = 15;
const int *ptr = &a; //2. we point our pointer to the mem address of “a”
a = 20; //3. we a= 20
//4. we output the *ptr that points to “a”
//so any changes of a will be reflected also to *ptr value.
NSLog(@”POINTER VALUE – %d”, *ptr); //20
NSDate
Adding interval to a date and create date from components (NSInteger values)
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:item.day];
[dateComps setMonth:item.month];
[dateComps setYear:item.year];
[dateComps setHour:item.hour];
[dateComps setMinute:item.minute];
//sample date is 2010-09-14 00:41:00
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
int minutesBefore = 1; //1 minute
//we are adding 60 seconds to our current date here...
NSDate *fireDate = [itemDate dateByAddingTimeInterval:-(minutesBefore*60)];
UIDevice
The UIDevice class provides a singleton instance representing the current device. From this instance you can obtain information about the device such as unique ID, assigned name, device model, and operating-system name and version.
You also use the UIDevice instance to detect changes in the device’s characteristics, such as physical orientation. You get the current orientation using the orientation property or receive change notifications by registering for the UIDeviceOrientationDidChangeNotification notification. Before using either of these techniques to get orientation data, you must enable data delivery using the beginGeneratingDeviceOrientationNotifications method. When you no longer need to track the device orientation, call the endGeneratingDeviceOrientationNotifications method to disable the delivery of notifications.
Similarly, you can use the UIDevice instance to obtain information and notifications about changes to the battery’s charge state (described by the batteryState property) and charge level (described by the batteryLevel property). The UIDevice instance also provides access to the proximity sensor state (described by the proximityState property). The proximity sensor detects whether the user is holding the device close to their face. Enable battery monitoring or proximity sensing only when you need it.
sample usage:
UIDevice* device = [UIDevice currentDevice];
NSString* deviceId = [device uniqueIdentifier];
--
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(detectOrientation) name:@"UIDeviceOrientationDidChangeNotification" object:nil];
--
if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) ||
([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) {
}
parentViewController – dismissing views
The parent view controller is responsible for dismissing the modal view controller it presented using the presentModalViewController:animated: method. If you call this method on the modal view controller itself, however, the modal view controller automatically forwards the message to its parent view controller.
To dismiss the PRESENTED modal view, use below that is right.
[[self parentViewController] dismissModalViewControllerAnimated:YES]; //right
[[picker parentViewController] dismissModalViewControllerAnimated:YES]; //right
[self dismissModalViewControllerAnimated:YES]; //wrong
Selectors
Selectors lets you perform methods during such events.
You can perform selectors with delays using this one below.
[self performSelector:@selector(method:) withObject:nil afterDelay:3];
UIAccelerometer
The UIAccelerometer class lets you register to receive acceleration-related data from the onboard hardware. As a device moves, its hardware reports linear acceleration changes along the primary axes in three-dimensional space. You can use this data to detect both the current orientation of the device (relative to the ground) and any instantaneous changes to that orientation. You might use instantaneous changes as input to a game or to initiate some action in your application.
UIAccelerometerDelegate:
The UIAccelerometerDelegate is a formal protocol, so your delegate object must implement the method it defines. The shared accelerometer object delivers the acceleration data to your delegate at the specified interval. It delivers these events on the main thread of your application when it is in the NSDefaultRunLoopMode run loop mode.
See codes below:
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
self.accelerometer = [UIAccelerometer sharedAccelerometer];
self.accelerometer.updateInterval = .1;
self.accelerometer.delegate = self;
}
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
labelX.text = [NSString stringWithFormat:@"%@%f", @"X: ", acceleration.x];
labelY.text = [NSString stringWithFormat:@"%@%f", @"Y: ", acceleration.y];
labelZ.text = [NSString stringWithFormat:@"%@%f", @"Z: ", acceleration.z];
self.progressX.progress = ABS(acceleration.x);
self.progressY.progress = ABS(acceleration.y);
self.progressZ.progress = ABS(acceleration.z);
}
Enumerations
TyfeDef is an alternative name assignment of an existing types. Enum makes your name assignment become an integral type and should only be used to declare variables which hold one of the values listed in the declaration (that is, one of kBlue, kRed, and kGreen). You can assign a ColorType variable another value by casting, though, so you have to be careful when reading enum values.
#1
typedef enum {
kBlue,
kRed,
kGreen
} ColorType;
#2
enum Ename { Bob, Mary, John };
typedef enum Ename EmployeeName;
UITouch
Generally we have these responders to work with touches. We can override these methods anyway.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
Sample usage:
- (void)touchesBegan: (NSSet *)touches withEvent:(UIEvent *)event {
//we acquire all touches happened in our view then we convert those touches to coordinates
UITouch *touch = [[event allTouches] anyObject];
CGPoint asd = [touch locationInView:self.view];
NSLog(@"X Touch Location...%f", asd.x);
NSLog(@"Y Touch Location...%f", asd.y);
}
NSThread
An NSThread object controls a thread of execution. You use an NSThread when you want to terminate or delay a thread or you want a new thread.
A thread is an executable unit. A task is made up of one or more threads. Each thread has its own execution stack and is capable of independent I/O. All threads share the virtual memory address space and communication rights of their task. When a thread is started, it is detached from its initiating thread. The new thread runs independently. That is, the initiating thread does not know the new thread’s state.
Usage:
[NSThread detachNewThreadSelector:@selector(myFunction) toTarget:self withObject:nil];
Inside Method myFunction.
- (void)myFunction {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// wait for 3 seconds before starting the thread, you don't have to do that. This is just an example how to stop the NSThread for some time
[NSThread sleepForTimeInterval:3];
[self performSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nil waitUntilDone:NO];
[pool release];
}
and this is inside makeMyProgressBarMoving
- (void)makeMyProgressBarMoving {
float actual = [threadProgressView progress];
threadValueLabel.text = [NSString stringWithFormat:@"%.2f", actual];
if (actual < 1) {
threadProgressView.progress = actual + 0.01;
[NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(makeMyProgressBarMoving) userInfo:nil repeats:NO];
}
else {
threadStartButton.hidden = NO;
//[NSThread exit];
}
}
UIPopOverController
- This works only in iPad from OS3.2 and so on.
- To use this class you need to have a viewController that is displayed inside this popup. See below example.
ViewController *viewController = [[ViewControlleralloc] initWithNibName:@"ViewController" bundle:nil];
UIPopoverController *aPopup = [[UIPopoverController alloc]initWithContentViewController:viewController];
aPopup.popoverContentSize = CGSizeMake(400.0f,180.0f);
viewController.aPopupController = aPopup;
aPopController is a member variable of our ViewController. This is used only if you have methods inside the viewController class to dismiss it. Like the code below.
[aPopupController dismissPopoverAnimated:YES];
NSLocal
- Used to detect Local languange and location
NSLocale *localInfo = [NSLocale currentLocale];
NSString *codePays = [localInfo objectForKey:NSLocaleLanguageCode];
UIPasteBoard
- All your copied strings are stored here.
UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
pasteBoard.items = nil; // Clear pasteboard to prevent pasting into other applications:
UIResponder
//Below is used to remove keyboard after editing
[textField resignFirstResponder];
UIActivityIndicatorView
//Show how to animate indicator from loading the webView to finish loading.
#pragma mark UIWebview delegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
[progressIndicator startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[progressIndicator stopAnimating];
}
UIMenuController
//Pop up buttons once you highlight uiTextField or UiWebview
//This can be disabled with the code below.
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
if ( [UIMenuController sharedMenuController] )
{
[UIMenuController sharedMenuController].menuVisible = NO;
}
}
NSArray – Random Sort
First you need to have a function that handles the randomization.
int randomSort(id obj1, id obj2, void *context ) {
// returns random number -1 0 1
return (arc4random()%3 - 1);
}
Then you could call this function to any array you wanted to sort randomly.
[arrayObject sortUsingFunction:randomSort context:nil];
UITabBar – Index of selected tabbar item
In order to get the selected index of the selectedItem (tabbaritem).. You only need to do this.
#pragma mark UI TAB BAR Delegate
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
NSLog(@"Selected Item Index...%d",[[tabBar items] indexOfObject:tabBar.selectedItem]);
}
UIImagePickerController
Image pickers helps users select images they want to use accordingly.
Note: UIImagePickerControllerDelegate should be included in your interface.
1. Using the the Photo Library, we have the code below.
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
picker.delegate = self;
//picker.allowsImageEditing = NO;
[self presentModalViewController:picker animated:YES];
[picker release];
2. Using the iPhone Camera , we have the code below.
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.delegate = self;
//picker.allowsImageEditing = NO;
[self presentModalViewController:picker animated:YES];
[picker release];
3. Using the iPhone Saved Photo Album , we have the code below.
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
picker.delegate = self;
//picker.allowsImageEditing = NO;
[self presentModalViewController:picker animated:YES];
[picker release];
Then, we use delegate methods to fetch image values from different source types. See code below.
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo
{
newImage.image = image; //this newImage is an outLet to your XIB which display a selected image.
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[[picker parentViewController] dismissModalViewControllerAnimated:YES];
}
UIButton
Setting up uiButton with states
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"btn_home2.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"btn_home1.png"] forState:UIControlStateSelected];
[button addTarget:self action:@selector(gobackToMainLibary:) forControlEvents:UIControlEventTouchUpInside];
button.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
[self.navigationBar addSubview:button];
error from Debugger: The program being debugged is not being run
If you have this kind of errors (also Error launching remote program: security policy error.) upon compiling application to simulator or your device. It has something to do with provisioning profiles.
Solution: Delete and re-install all your Provisioning Profiles:
- Navigate your XCode Organizer window
- Select your device from Devices list
- Remove your Provisioning Profiles from Provisioning Section
- Download your Provisioning Profiles from your developer.apple.com account
- Re-install your profiles moving all downloaded files over the Xcode icon on the Dock
Push Notification
To send Push Notifications to a device, you need a device token. Device token is generated by Apple from Device ID and Application ID, so this is unique per device and per application.
See notes here:
http://code.google.com/p/apns-php/wiki/ObjectiveC
http://iphonesdkdev.blogspot.com/2009/03/apple-push-notification-service-apns.html
Native Animation
Uses QuartzCore to animate objects
#import <QuartzCore/QuartzCore.h>
TickerViewController *tickerController = [[TickerViewController alloc] initWithNibName:@"TickerViewController" bundle:nil];
[myWebview addSubview:tickerController.view];
CABasicAnimation *theAnimation;
theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
theAnimation.duration=10;
theAnimation.repeatCount=2;
theAnimation.autoreverses=NO;
theAnimation.fromValue=[NSNumber numberWithFloat:0];
theAnimation.toValue=[NSNumber numberWithFloat:-768];
//[view.layer addAnimation:theAnimation forKey:@"animateLayer"];
[[tickerController view].layer addAnimation:theAnimation forKey:@"animateLayer"];
[tickerController release];
PDF Printing
//used to print PDF
See this link: http://www.danandcheryl.com/2010/05/how-to-print-a-pdf-file-using-cocoa
Happy Coding