The path to ios: Objective-C block syntax. NSDate and NSDateFormatter, objective-c.nsdate

Source: Internet
Author: User
Tags date1

The path to ios: Objective-C block syntax. NSDate and NSDateFormatter, objective-c.nsdate

I. Block syntax

Block Syntax: anonymous functions can be defined within a function.

Format: ^ return value type (parameter list) {function body}. The return value type can be omitted.

Simple block exercises:

①. Calculate the maximum value of two numbers

// Int (^) (int, int) // block type int (^ max) (int, int) = ^ (int a, int B) {// return a> B? A: B ;}; int value = max (4, 6); printf ("% d", value );
②. Convert an integer into a string object
        typedef void (^Exchange)(int);        Exchange  change = ^(int number) {            NSString *string = [[NSString alloc] initWithFormat:@"%d",number];            NSLog(@"%@",string);        };        change(5);
③. Convert an integer into an NSMumber object
     typedef  NSNumber *(^EXC)(int);        EXC exchange = ^ NSNumber *(int number) {            return @(number);        };        NSNumber *number = exchange(5);        NSLog(@"%@",number);
4. Input A String object and return all objects in uppercase.
      typedef NSString *(^UPPER)(NSString *);        UPPER upperString = ^NSString *(NSString *string) {            return [string uppercaseString];        };                NSString *temp = @"sdsdfasdf";        NSString *num = upperString(temp);        NSLog(@"%@",num);
⑤ Calculate the number of OC array elements,
     typedef NSUInteger (^Count)(NSArray *);       Count getCount = ^NSUInteger (NSArray *arr) {            return [arr count];        };        NSArray *ar1 = @[@"sadf",@"asdf",@"dsfg",@"fdg"];        NSUInteger count = getCount(ar1);        NSLog(@"%ld",count);
6. Define a block to compare two integers.
        typedef NSComparisonResult (^Compare)(int,int);        Compare compare = ^NSComparisonResult(int a,int b) {            //return [@(a) compare :@(b)];            return a > b ? NSOrderedDescending : a == b ?                                          NSOrderedSame : NSOrderedAscending;        };        NSComparisonResult x =  compare(5,6);        NSLog(@"%ld",x);//-1
7. Comparison of Two string objects
     typedef NSComparisonResult (^CompareString)(NSString *,NSString *);        CompareString com = ^NSComparisonResult(NSString *str1,NSString *str2) {            return [str1 compare:str2];        };        NSString *temp1 = @"dasf";        NSString *temp2 = @"das35f";        NSComparisonResult tem  = com(temp1,temp2);        NSLog(@"%ld",tem);
Sort. block to sort Arrays

    NSArray *ar = @[@"ads",@"dd",@"ff",@"hh"];    NSArray *ar1 = [ar sortedArrayUsingComparator:^(id num1,id num2) {        return -[(NSString *)num1 compare: (NSString *)num2];    }];    NSLog(@"%@",ar1);

2. Relationship between block and local variables and global variables

_ Block int num = 1; // _ block after modification, you can modify the local Variable void (^ addNum) () = ^ void () {int c = num * 10; // The block can access the external local variable num ++. // The local variable is accessed internally, but the local variable cannot be modified. if _ block is used for modification, you can modify printf ("% d", c) ;}; addNum ();

Ii. Common NSDate and NSDateFormatter applications

①. Get the time of the current Zero Time Zone

   NSDate *date = [NSDate date];   NSLog(@"%@",date);
②. Obtain the time of tomorrow at this time

   NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:60 * 60 * 24];   NSLog(@"%@",tomorrow);
③ Obtain the current time of yesterday
  NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-60 * 60 * 24];  NSLog(@"%@",yesterday)
④ Calculate the time at this time by 2014/12/1/29
   NSDate *now = [NSDate dateWithTimeIntervalSince1970:                          (11 * 366 + 33 * 365)* 24 * 3600 + 362 * 24 * 3600];   NSLog(@"%@",now);
⑤ Calculate the time at this time using 2001/1/1 // default: 2001/1/1
  NSDate *now1 = [NSDate dateWithTimeIntervalSinceReferenceDate:                                (3 * 366 + 11 * 365)* 24 * 3600 - 3 * 24 * 3600];  NSLog(@"%@",now1);
6. Get the two time intervals

NSTimeInterval interval = [date1 timeIntervalSinceDate: date2]; // NSTimeInterval NSLog of the double type (@ "%. 1f", interval );
7. Compare the morning and evening dates, and return the morning and evening dates
 NSDate *dt1 = [date1 earlierDate:date2]; NSDate *dt2 = [date1 laterDate:date2]; NSLog(@"%@",dt1); NSLog(@"%@",dt2);
Same. Determine if the date is the same
BOOL isEqual = [date1 is1_todate: date2]; if (isEqual) {NSLog (@ "equal");} else {NSLog (@ "not equal ");}
Iii. Date Format class NSDateFormatter
①. Convert the NSDate object into a date string according to the specified date format.
- (NSString *)stringFromDate:(NSDate *)date;
The Code is as follows:

NSDate * date = [NSDate date]; // obtain the current time NSDateFormatter * formatter = [[NSDateFormatter alloc] init]; // set the format. // HH --- indicates the 24-hour system, and hh --- indicates the 12-hour aa system. Afternoon/morning, EEE Tuesday [formatter setDateFormat: @ "yyyy-MM-dd HH: mm: ss EEE aa "];/[formatter setDateFormat: @" MM dd-month EEE aaHH: mm "]; // converts the format NSString * string = [formatter stringFromDate: date]; NSLog (@ "% @", string );

2. Convert the date string into an NSDate object according to the specified date format 
NSDateFormatter * formatter = [[NSDateFormatter alloc] init]; NSString * string1 = @ ", January 1, May 01, 2014"; NSLog (@ "% @", string1 ); // For NSDate objects, the time is always zero time zone // HH --- indicates the 24-hour system, and hh --- indicates the 12-hour system [formatter setDateFormat: @ "MM-dd-yyyy HH: mm: ss seconds"]; NSDate * date1 = [formatter dateFromString: string1]; NSLog (@ "% @", date1 );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.