主要解释以下两者区别
[NSURL URLWithString:filePath]
[NSURL fileURLWithPath:filePath];
一、概念
URL :协议头 + 主机地址 + 资源路径 如果访问的地址是本机的,那么主机地址可以省略;路径是不用包含协议头和主机的
路径:?
二、测试
NSDictionary *dic = @{@"name":@"xiaoqiang"};
NSString *documentPath = [NSString stringWithFormat:@"%@/Documents",NSHomeDirectory()];
NSString *filePath = [NSString stringWithFormat:@"%@/name.plist",documentPath];
NSString *fileURl = [NSString stringWithFormat:@"file:///%@",filePath];
//file:////Users/huihuadeng/Library/Developer/CoreSimulator/Devices/9F943056-7AD1-4A4E-B9E9-AE186A833AE6/data/Containers/Data/Application/188085CE-E77D-40CA-B419-566B2FCBD50A/Documents/name.plist
NSURL *url1 = [NSURL URLWithString:fileURl];
//:file:///Users/huihuadeng/Library/Developer/CoreSimulator/Devices/9F943056-7AD1-4A4E-B9E9-AE186A833AE6/data/Containers/Data/Application/188085CE-E77D-40CA-B419-566B2FCBD50A/Documents/name.plist
NSURL *url2 = [NSURL fileURLWithPath:filePath];
///Users/huihuadeng/Library/Developer/CoreSimulator/Devices/9F943056-7AD1-4A4E-B9E9-AE186A833AE6/data/Containers/Data/Appl ... me.plist
NSURL *url3 = [NSURL URLWithString:filePath];
// [dic writeToFile:filePath atomically:YES];//正常
// [dic writeToURL:url1 error:nil];//正常
// [dic writeToURL:url2 error:nil];//正常
[dic writeToURL:url3 error:nil];//非正常
如上所述,推测 [NSURL URLWithString:filePath]; API仅仅是把string转化为URL对象,不做任何处理
[NSURL fileURLWithPath:filePath];会在路径前添加协议头 file:///
网友评论