当前位置:网站首页>[OC foundation framework] - string and date and time >

[OC foundation framework] - string and date and time >

2022-07-06 08:57:00 About Xiaosi

OC The string in

NSString and NSMutableString

  • OC String in
    A string is a sequence of characters ,OC There is 2 A string :
    NSString and NSMutableString
  • among NSString Is an immutable string of character sequences
  • NSMutableString Represents a string that can be changed from a character sequence

NSString The function of

NSString Represents an immutable string of character sequences ,NSString The functions are as follows

  • Create a character other than , To create a word line string, you can use init Example method at the beginning , Can also be used to string The first class method , It can also be used directly @ Gives the string direct quantity in the form of .
  • Read file or network URL To initialize the string .
  • Put the character into the file or URL•
  • Get string length , You can get the number of characters included in the string , You can also get the number of bytes included in the string .
  • Gets the character or byte in the string , You can get the character at the specified position , You can also accept characters in a specified range
  • Get the corresponding string C Style string
  • Connection string .
  • Delimited string
    • Find the specified character and substring in the string . Replace string .
  • Compare strings ,
    String size comparison . Case conversion of characters in a string .

NSString- There are three ways to create functions

  • Will a Unicode Array value grab conversion string
  • hold c The style string is converted to NSString object
  • Read file initialization NSString object
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
    
    // Example 3 Species creation NSString How objects work 
    @autoreleasepool {
    
        unichar data[6] = {
    1,2,3,4,5,6};
        //1. unicode  Initialize string 
        //  Convert the array into the corresponding   character 
        NSString* str = [[NSString alloc] initWithCharacters:data length:6];
        NSLog(@"%@", str);
        
        
        //2. take c The style string is converted to NSString  object 
        char *cstr = "hello ,3G!";
        NSString* str2 = [NSString stringWithUTF8String: cstr];
        NSLog(@"%@", str2);
        
        //3. Writes the string to the specified file 
        [str2 writeToFile:@"myFile,txt"
               atomically:YES
               encoding:NSUTF8StringEncoding
                    error:nil];
        //  Read file contents , Initialize the string with the contents of the file 
        NSString *str3 = [NSString stringWithContentsOfFile:@"NSStringTest.m"
            encoding:NSUTF8StringEncoding
            error:nil];
        NSLog(@"%@", str3);
    }
    return 0;
}

        
2022-05-21 20:10:36.914213+0800 OC- character string [5723:868393] \^A\^B\^C\^D\^E\^F
2022-05-21 20:10:36.914410+0800 OC- character string [5723:868393] hello ,3G!
2022-05-21 20:10:36.914916+0800 OC- character string [5723:868393] (null)
Program ended with exit code: 0

NSString- Common functions of

To create a string, you must use it , Next, let's look at the call NSString* I won't go into details about the functional method of

#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
    
    @autoreleasepool {
    
        NSString* str = @"hello";
        NSString* book = @"《iOS Xiaobaishu 》";
        //1. stay str Append string after 
        //  The original string object remains unchanged , The newly generated string is assigned to str Variable 
        str = [str stringByAppendingString:@" , Meng Hao !"];
        NSLog(@"%@", str);
       
        // 2. Get the corresponding string c style 
        const char *cstr = [str UTF8String];
        NSLog(@"c Language string  :%s", cstr);
        
        // 3. Append variable after string   String 
        //  The original string object remains unchanged , The newly generated string is assigned to str Variable , Pay attention to and 1 The difference between 
        str = [str stringByAppendingFormat:@"%@ fit 3g iOS Group of leopards reading ", book];
        NSLog(@"%@", str);
        
        //4.
        NSLog(@"str The number of characters in is  %lu", [str length]);
        NSLog(@"str according to  UTF-8  The number of bytes after character set decoding is %lu", [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
        
        //5. obtain str front 10 A string of characters 
        NSString *str1 = [str substringToIndex:10];
        NSLog(@"%@", str1);
        
        //6. obtain str Start with the fifth character , And all the following characters 
        NSString *str2 = [str substringFromIndex:5];
        NSLog(@"%@", str2);
        
        //7. obtain str Start with the fifth character , And back 15 A string of characters 
        NSString *str3 = [str substringWithRange:NSMakeRange(5, 15)];
        NSLog(@"%@", str3);
        
        //8. Find the position where a string appears 
        NSRange pos = [str rangeOfString:@"iOS"];
        NSLog(@"iOS The starting position of the appearance is  %ld,  The length is  %ld", pos.location, pos.length);
        
        //9. Capitalize all strings 
        str = [str uppercaseString];
        NSLog(@"%@", str);
        
    }
    return 0;
}

 Insert picture description here

NSRange Variable

In the penultimate method of string function, we Set up a pos Variable to find iOS Where the character appears
NSRange The class variables , It's not a class , It's just a well-defined Coprinus comatus , Contains
length and int value They represent the starting position and length respectively
establish NSRange Variables need to be NSMakeRange () function

Variable string -NSMutableString

NSString Once the string is created , The sequence of strings contained in this object is immutable , Until it is destroyed
NSMutableString Object represents a string with variable character sequence , and NSMutableString yes NSString Subclasses are therefore described above NSString Included methods NSMutableString Directly callable

  • because NSMutableString It is variable, so we don't need to assign another value to NSMutableString Created str Variable
  • Here is a brief answer, but I don't want to repeat it
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
    
    @autoreleasepool {
    
        NSMutableString *str = [NSMutableString stringWithString:@"hello"];
        [str appendString:@"iOSSSSSS"];
        // Directly append without assignment 
        NSLog(@"%@“, str");
        
        // The character sequence contained in the character output is variable, so the New Year greeting itself occurs, so there is no need to re assign 
        [str appendFormat:@" Suitable for me to study "];
        NSLog(@"%@", str);
        
    }
    return 0;
}

2022-05-22 14:55:52.138802+0800 OC- character string [7570:1175044] (null),str
2022-05-22 14:55:52.139023+0800 OC- character string [7570:1175044] helloiOSSSSSS Suitable for me to study 
Program ended with exit code: 0

Date and time (NSDate)

NSDate object

NSDate Object represents date and time ,OC It not only provides class methods to create NSDate object , It also provides a lot of init start Method to initialize NSDate object

NSDate Class

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    
    @autoreleasepool {
    
        //1. Get , The time of the NSDate------ Class method 
        NSDate* date1 = [NSDate date];
        NSLog(@" It's Beijing time  %@", date1);
        
        //2. Get from the current time   Date after one day =------- Example method 
        NSDate* date2 = [[NSDate alloc] initWithTimeIntervalSinceNow:3600 * 24];
        NSLog(@" %@", date2);
        //3. Get from the current time  3 Date within days ------- Example method 
        NSDate* date3 = [[NSDate alloc] initWithTimeIntervalSinceNow:-3 * 3600 * 24];
        NSLog(@" %@", date3);
//
        //4.  from 1970 year 1.1  Start  20  Date after year -------- Class method 
        NSDate *date4 = [NSDate dateWithTimeIntervalSince1970:3600 * 24 * 366 * 20];
        NSLog(@" %@", date4);
        
        //5. Get the... Of the current system NSLocale
        NSLocale* cn = [NSLocale currentLocale];
        //  obtain NSdate
        NSLog(@"%@", [date1 descriptionWithLocale:cn]);
        
        //  Get current 2 The earlier of the dates ------- Class method 
        NSDate* earlier = [date1 earlierDate: date2];
        //  Get current 2 The later of the two dates ------- Class method 
        NSDate * later = [date1 laterDate:date2];
        
        //compare  Method returns NScomparisonResult Enumerated values 
//  Enumeration contains 
        //NSOrderedAscending,NSOrderedSame, NSOrderedDescending
        //  They represent   call compare  The date of is before the compared date   identical   after 
        switch ([date1 compare:date3]) {
    
            case NSOrderedAscending:
                NSLog(@"date1  be located  date3  Before ");
                break;
            case NSOrderedSame:
                NSLog(@"date1  and  date3 It's the same day ");
                break;;
            case NSOrderedDescending:
                NSLog(@"date1  be located  date3  Before ");
                break;;
        }
        
        
        NSLog(@"date1  And  date3  Time difference %g s", [date1 timeIntervalSinceDate:date3]);
        NSLog(@"date3  Not as good as now  %g s", [date3 timeIntervalSinceNow]);
    }
    return 0;
}

2022-05-23 17:42:19.620894+0800 OC- date NSDate[9627:1522836]  It's Beijing time  2022-05-23 09:42:19 +0000
2022-05-23 17:42:19.620990+0800 OC- date NSDate[9627:1522836]  Tue May 24 17:42:19 2022
2022-05-23 17:42:19.621012+0800 OC- date NSDate[9627:1522836]  Fri May 20 17:42:19 2022
2022-05-23 17:42:19.621027+0800 OC- date NSDate[9627:1522836]  Tue Jan 16 08:00:00 1990
2022-05-23 17:42:19.621300+0800 OC- date NSDate[9627:1522836] 2022 year 5 month 23 Japan   Monday   China standard time  17:42:19
2022-05-23 17:42:19.621325+0800 OC- date NSDate[9627:1522836] date1  be located  date3  Before 
2022-05-23 17:42:19.621342+0800 OC- date NSDate[9627:1522836] date1  And  date3  Time difference 259200 s
2022-05-23 17:42:19.621357+0800 OC- date NSDate[9627:1522836] date3  Not as good as now  -259200 s
Program ended with exit code: 0

NSDate Explanation of method code

  • establish NSDate The class method of is basically similar to the instance method , Class method date The instance method starts with init start , Once you get it NSDate object Two NSDate Size can be compared between objects , Calculate the time difference
  • NSLocale Represents a language , International environment, such as Chinese You can go through NSLocale Object to represent , The same date in different languages, international environment The displayed characters are different .

Date formatter (NSDate Formatter)

NSDate Formatter Represents a date formatter , Its function is to complete NSDate and NSString Conversion between

NSDate Formatter call

1. Create a NSDateFormatter object .
2. call NSDateFormatter Of setDate Style:、setTimestyle: Method to set the format date 、 Among the styles of time , date 、 The time style supports the following enumeration values

  • >NSDateFormatterNostyle: Do not display date 、 The style of time .
  • > NSDateFormatter Shortstyle: Show “ short ” Date 、 Time style .
  • > NSDateFormatterMediumStyle: Show “ secondary ” Date 、 Time style .
  • NSDateFormatterLongstyle: Show “ Long ” Date 、 Time style .
  • NSDateFormatterFullStyle: Show “ complete ” Date 、 Time style
    If you plan to use your own format template , Call NSDateFormatter Of setDate Format: Method to set the date 、 The template of time .
  • 3 . If necessary NSDate Convert to NSString, Call NSDateFormatter Of stringFromDate: Method
    Execute formatting ; If necessary NSString Convert to NSDate, Call NSDateF ormatter Of
    dateFromString: Method to perform formatting .

The calendar (NSCalendar) And ( The date of the component NSDatecomponents)

The role of two classes

  • In order to be treated separately NSDate The data of each field contained in the object ,Foundation The framework provides NSCalendar object , This object contains the following two common methods .

---------------------------------------------------------- (SDateComponents * ) components:fromDate: from NSDate Year of withdrawal 、 month 、 Japan 、 when 、 Information of each time field in minutes and seconds .

dateFromComponents: (NSDateComponents*)comps: Use comps The year the object contains 、 month 、 Japan 、 when 、 branch 、 Seconds to create NSDate
Both methods use one NSDateComponents object , This object is specifically used to encapsulate year 、 month 、 Japan 、 when 、 branch 、 Second information of each time field . This object is very simple , It only contains the right year、month. date、day、hour、
minute、second、week、weekday And other fields setter and getter Method

from NSDate Get each time field separately in the object The numerical method of is as follows

  • ① establish NSCalendar object .
  • ② call NSCalendar Of components: fromDate: Method to get NSDate The value of each time field in the object
    This method returns a NSDateComponents object .
  • ③ call NSDateComponents Object's getter Method to get the value of each time field .

Use the values of each time field to initialize NSDate Object steps are as follows .

  • ① establish NSCalendar object .
  • ② Create a NSDateComponents object , Calling the setter Method to set the value of each time field .
  • ③ call NSCalendar Of dateFromComponents: (NSDateComponents*) Method initialization NSDate Yes
    Methods like this will return a NSDate object .
demonstration

 Insert picture description here

 Insert picture description here

原网站

版权声明
本文为[About Xiaosi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060850139239.html