key gợi nhớ mã lệnh trong objective-c ( phục vụ mục đích cá nhân 😀 )
Macros: lệnh đơn độc
#import <Foundation/Foundation.h>
#define PI 3.14159
#define RAD_TO_DEG(radians) (radians * (180.0 / PI))
Typedef: tạo 1 cấu trúc mới hoặc tái tạo cấu trúc cũ
typedef unsigned char ColorComponent;
ColorComponent red = 255;
NSLog(@” %hhu”,red);
Struct:
typedef struct {
unsigned char red;
unsigned char green;
unsigned char blue;
} Color;
Color carColor = {255, 160, 0};
NSLog(@”Your paint job is (R: %hhu, G: %hhu, B: %hhu)”,
carColor.red, carColor.green, carColor.blue);
Enums:
typedef enum {FORD, HONDA,NISSAN,PORSCHE
} CarModel;
Primitive Array: array gốc của C, cao hơn là NSArray, NSMutableArray
int years[4] = {1968, 1970, 1989, 1999};
years[0] = 1967;
for (int i=0; i<4; i++) {
NSLog(@”The year at index %d is: %d”, i, years[i]);
}
Pointers: & trả về memory address, * trả về nội dung,có thể gián =NULL
int year = 1967; // Define a normal variable
int *pointer; // Declare a pointer that points to an int
pointer = &year;// Find the memory address of the variable
NSLog(@”%d”, *pointer);//get its value from the address
char model[5] = {‘H’, ‘o’, ‘n’, ‘d’, ‘a’};
char *modelPointer = &model[0];
for (int i=0; i<5; i++) {
NSLog(@”Value at memory address %p is %c”,
modelPointer, *modelPointer);
modelPointer++;
}
NSLog(@”The first letter is %c”, *(modelPointer – 5));
Pointers in Object-C
NSString *anObject; // An Objective-C object
anObject = NULL; // This will work
anObject = nil; // But this is preferred
int *aPointer; // A plain old C pointer
aPointer = nil; // Don’t do this
aPointer = NULL; // Do this instead
Run C, C++ in Objective-C: đổi đuôi file thành *.mm
Random:
arc4random_uniform((maximum – minimum) + 1) + minimum;
trả về giá trị giứa 0 và 1 số bất kì
Close Keyboard: add Tap Gesture Reconizer -> Layout ->add event cho Tap…
[<ten textbox> resignFirstResponder];
Currency to number
-(void) currencyToDouble: (NSString*) currency{
NSNumberFormatter *numberFormatter = [[ NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle ];
NSNumber *number = [numberFormatter numberFromString:currency];
NSLog(@”%@ convert to number is: %@”,currency,number);
}
NSDate to part:
-(void) datePart:(NSString *)dateString withFormat:(NSString *)format toGetPart:(NSString*) typeOfDate{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:format];
NSDate *date = [dateFormat dateFromString:dateString];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date];
if([[typeOfDate lowercaseString] isEqualToString:@”day”])
NSLog(@”Day is:%d”, (int)[components day]);
if([[typeOfDate lowercaseString] isEqualToString:@”month”])
NSLog(@”Month is: %d”, (int)[components month]);
if([[typeOfDate lowercaseString] isEqualToString:@”year”])
NSLog(@”Year is: %d”,(int)[components year]);
}
NSPredicate:
NSMutableArray *oldSkoolFiltered = [[NSMutableArray alloc] init];
for (Book *book in bookshelf) {
if ([book.publisher isEqualToString:@”Apress”]) {}
}
NSPredicate *predicate =[ NSPredicate predicateWithFormat:@”publisher == %@”, @”Apress” ];
NSArray *filtered= [ bookshelf filteredArrayUsingPredicate:predicate];
//Regular Expressions
[NSPredicate predicateWithFormat:@”title MATCHES ‘.*(iPhone|iPad).*'”]; // iphone or ipad in title
//Operation
NSArray *favoritePublishers = [NSArray arrayWithObjects:@”Apress”, @”O’Reilly”, nil];
predicate = [NSPredicate predicateWithFormat:@”publisher IN %@”, favoritePublishers];
//using KVC compliant
predicate=[NSPredicate predicateWithFormat: @”authors.lastName CONTAINS[cd] %@” , @”Mark” ];
Protocols
@protocol PrintProtocolDelegate
– (void)processCompleted;
@end
@interface PrintClass :NSObject
{ id delegate; }
– (void) printDetails;
– (void) setDelegate:(id)newDelegate;
@end
@implementation PrintClass
– (void)printDetails{
NSLog(@”Printing Details”);
[delegate processCompleted];
}
– (void) setDelegate:(id)newDelegate{
delegate = newDelegate;
}
@end
@interface SampleClass:NSObject<PrintProtocolDelegate>
– (void)startAction;
@end
@implementation SampleClass
– (void)startAction{
PrintClass *printClass = [[PrintClass alloc]init];
[printClass setDelegate:self];
[printClass printDetails];
}
-(void)processCompleted{
NSLog(@”Printing Process Completed”);
}
@end
int main(int argc, const char * argv[]){
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass startAction];
[pool drain];
return 0;
}
UI Switch
On/off : <ten switch>.isOn
[<ten switch> setOn:<BOOL> animated:YES];
UI Segmented Controll: index of which clicked
[sender selectedSegmentIndex]==0
Fix Table Line:
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
}
Send Notification between View
receive class
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataReceived:) name:@”addData” object:nil];
-(void)dataReceived:(NSNotification *)noti
{
NSDictionary *dataController = noti.object;
BirdSighting *bird = [dataController objectForKey:@”BirdSighting”];
[self.dataController addBirdSightingWithSighting:bird];
NSLog(@”dataReceived :%@”, noti.object);
}
sender class >
[[NSNotificationCenter defaultCenter] postNotificationName:@”addData” object:[NSDictionary dictionaryWithObject:bird forKey:@”BirdSighting”]];
Change style of Tab Bar
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIColor whiteColor], NSForegroundColorAttributeName,
nil] forState:UIControlStateNormal];
UIColor *titleHighlightedColor = [UIColor colorWithRed:153/255.0 green:192/255.0 blue:48/255.0 alpha:1.0];
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
titleHighlightedColor, NSForegroundColorAttributeName,
nil] forState:UIControlStateHighlighted];
Get Cell of Table View
NSArray *cells = [tableView visibleCells];
NSMutableArray *cells = [[NSMutableArray alloc] init];
for (NSInteger j = 0; j < [tableView numberOfSections]; ++j)
{
for (NSInteger i = 0; i < [tableView numberOfRowsInSection:j]; ++i)
{
[cells addObject:[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:j]]];
}
}
for (CustomTableViewCell *cell in cells)
{
UITextField *textField = [cell textField];
NSLog(@”%@”; [textField text]);
}
Add Navigation Button Item
UIBarButtonItem *leftBarButtonEdit = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@”Checked”] style:UIBarButtonItemStylePlain target:self action:@selector(btnEditField:)];
UIBarButtonItem *leftBarButtonDelete = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@”Delete”] style:UIBarButtonItemStylePlain target:self action:@selector(btnDeleteField:)];
[self.navigationItem setRightBarButtonItems:@[leftBarButtonEdit,leftBarButtonDelete] animated:YES];
Change Status Bar Color
Open the info.plist file of your app and set the UIViewControllerBasedStatusBarAppearance to NO
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
Switch View Controller with animation
-(void)switchViewController:(NSString *)storyboardID{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@”Main” bundle:nil];
UIViewController *visibleViewController = [storyboard instantiateViewControllerWithIdentifier:storyboardID];
// [UIView transitionWithView:self.window
// duration:0.5
// options:UIViewAnimationOptionTransitionCurlUp
// animations:^{ self.window.rootViewController = visibleViewController; }
// completion:nil];
CATransition *transition = [CATransition animation];
transition.duration = 0.5;
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromRight;
[transition setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[self.window.layer addAnimation:transition forKey:nil];
self.window.rootViewController = visibleViewController;
}
Alert View with Indicator
UIAlertView * myAlertView = [[UIAlertView alloc] initWithTitle:@”Loading” message:@””
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil, nil];
UIActivityIndicatorView *loading = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
loading.center = self.view.center;
loading.hidesWhenStopped = true;
loading.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
[myAlertView setValue:loading forKey:@”accessoryView”];
[loading startAnimating];
[myAlertView show];
int64_t delayInSeconds = 3; // Your Game Interval as mentioned above by you
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[myAlertView dismissWithClickedButtonIndex:0 animated:YES];
[appDelegate switchViewController:@”SlideMenuView”];
});
http://rypress.com/tutorials/objective-c
Số lượt thíchSố lượt thích