1.NSArray排序
- Foundation自带类排序
NSArray *arr = @[@(1), @(9), @(5), @(2)];
NSArray *newArr = [arrsortedArrayUsingSelector:@selector(compare:)];
- 自定义类排序
NSArray *arr = @[p1, p2, p3, p4, p5];
// 默认按照升序排序
NSArray *newArr = [arrsortedArrayWithOptions:NSSortConcurrentusingComparator:^NSComparisonResult(Person *obj1, Person *obj2) {
return obj1.age > obj2.age;
}];
NSLog(@"%@", newArr);
2.NSArray数据写入到文件中
```
NSArray *arr = @[@"lnj", @"lmj", @"jjj", @"xcq"];
BOOL flag = [arrwriteToFile:@"/Users/LNJ/Desktop/persons.plist" atomically:YES];
NSLog(@"%i", flag);
```
3.从文件中读取数据到NSArray中
NSArray*newArr = [NSArrayarrayWithContentsOfFile:@"/Users/LNJ/Desktop/persons.xml"];
NSLog(@"%@", newArr);
4.把数组元素链接成字符串
- (NSString *)componentsJoinedByString:(NSString *)separator;
这是NSArray的方法, 用separator作拼接符将数组元素拼接成一个字符串
NSArray *arr = @[@"lnj", @"lmj", @"jjj", @"xcq"];
NSString *res = [arrcomponentsJoinedByString:@"*"];
NSLog(@"res = %@", res);
输出结果:
lnj*lmj*jjj*xcq
```
2.字符串分割方法
- (NSArray *)componentsSeparatedByString:(NSString *)separator;
这是NSString的方法,将字符串用separator作为分隔符切割成数组元素
NSString *str = @"lnj-lmj-jjj-xcq";
NSArray *arr = [strcomponentsSeparatedByString:@"-"];
NSLog(@"%@", arr);
输出结果:
(
lnj,
lmj,
jjj,
xcq
)
int main(intargc, constchar * argv[]) {
// NSURL *url = [NSURL alloc] initWithString:<#(NSString *)#>
/*
// URL = 协议头://主机地址/路径
NSString *path = @"file://192.168.13.10/Users/xiaomage/Desktop/课堂共享/day17/note/lnj.txt";
NSLog(@"url编码前: %@", path);
path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"url编码后: %@", path);
*/
/*
// 如果访问本机的文件, 可以省略主机地址
NSString *path = @"file:///Users/Desktop/课堂共享/day17/note/lnj.txt";
NSLog(@"url编码前: %@", path);
path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"url编码后: %@", path);
NSURL *url = [NSURL URLWithString:path];
*/
// 上面的几种方法不可以的原因是因为URL中包含了中文, 如果URL中包含了中文, 必须对URL进行一次转码
// fileURLWithPath创建出来的URL都是file:// 协议的
/*
NSURL *url = [NSURL fileURLWithPath:@"/Users/xiaomage/Desktop/课堂共享/day17/note/lnj.txt"];
NSError *error = nil;
NSString *str = [NSStringstringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
if (error == nil) {
NSLog(@"str = %@", str);
}else{
NSLog(@"error = %@", [error localizedDescription]);
}
*/
/*
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
NSString *str = [NSStringstringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"str = %@", str);
*/
NSString *str = @"abcdef";
NSURL *url = [NSURLfileURLWithPath:@"/Users/xiaomage/Desktop/123.txt"];
[strwriteToURL:urlatomically:YESencoding:NSUTF8StringEncodingerror:nil];
// 注意点: 如果重复写入, 后一次写入的会覆盖前一次写入的内容
NSString *str2 = @"我们号";
[str2writeToURL:urlatomically:YESencoding:NSUTF8StringEncodingerror:nil];
return0;
}
|
|