当前位置:网站首页>[OC foundation framework] - string and date and time >
[OC foundation framework] - string and date and time >
2022-07-06 08:57:00 【About Xiaosi】
List of articles
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;
}
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
边栏推荐
- Shift Operators
- 可变长参数
- ROS compilation calls the third-party dynamic library (xxx.so)
- 704 binary search
- 项目连接数据库遇到的问题及解决
- [OC-Foundation框架]-<字符串And日期与时间>
- LeetCode:39. Combined sum
- What is an R-value reference and what is the difference between it and an l-value?
- Detailed explanation of heap sorting
- 软件压力测试常见流程有哪些?专业出具软件测试报告公司分享
猜你喜欢
Excellent software testers have these abilities
[OC-Foundation框架]---【集合数组】
自定义卷积注意力算子的CUDA实现
[embedded] print log using JLINK RTT
LeetCode:221. 最大正方形
CUDA realizes focal_ loss
Mise en œuvre de la quantification post - formation du bminf
广州推进儿童友好城市建设,将探索学校周边200米设安全区域
Simple use of promise in uniapp
JVM quick start
随机推荐
R language ggplot2 visualization: place the title of the visualization image in the upper left corner of the image (customize Title position in top left of ggplot2 graph)
opencv+dlib实现给蒙娜丽莎“配”眼镜
BN folding and its quantification
LeetCode:39. 组合总和
【文本生成】论文合集推荐丨 斯坦福研究者引入时间控制方法 长文本生成更流畅
MongoDB 的安装和基本操作
Leetcode: Jianzhi offer 03 Duplicate numbers in array
Target detection - pytorch uses mobilenet series (V1, V2, V3) to build yolov4 target detection platform
Revit secondary development Hof method calls transaction
TP-LINK enterprise router PPTP configuration
Fairguard game reinforcement: under the upsurge of game going to sea, game security is facing new challenges
LeetCode:26. 删除有序数组中的重复项
pytorch查看张量占用内存大小
LeetCode:836. Rectangle overlap
Cesium draw points, lines, and faces
如何有效地进行自动化测试?
注意力机制的一种卷积替代方式
KDD 2022 paper collection (under continuous update)
After reading the programmer's story, I can't help covering my chest...
SimCLR:NLP中的对比学习