为什么我不能将字符串附加到NSURL?

时间:2014-08-18 00:40:21

标签: swift nsurl writetofile

将.txt文件组件附加到URL路径不起作用:

var error:NSError?
let manager = NSFileManager.defaultManager()
let docURL = manager.URLForDirectory(.DocumentDirectory, inDomain:.UserDomainMask, appropriateForURL:nil, create:true, error:&error)
docURL.URLByAppendingPathComponent("/RicFile.txt") <-- doesn't work

通过调试器:

file:///Users/Ric/Library/Developer/CoreSimulator/Devices/
<device id>/data/Containers/Data/Application/<app id>/Documents/

使用 docURL 将字符串写入文件由于缺少文件名而无法正常工作。

原因(通过错误):

  

&#34;操作无法完成。是目录&#34;

所以问题:为什么以下工作没有?

docURL.URLByAppendingPathComponent("/RicFile.txt")

2 个答案:

答案 0 :(得分:19)

URLByAppendingPathComponent:不会改变现有的NSURL,它会创建一个新的let directoryURL = manager.URLForDirectory(.DocumentDirectory, inDomain:.UserDomainMask, appropriateForURL:nil, create:true, error:&error) let docURL = directoryURL.URLByAppendingPathComponent("/RicFile.txt") 。来自documentation

  

URLByAppendingPathComponent:返回通过附加a创建的新URL   路径组件到原始URL。

您需要将方法的返回值分配给某个东西。例如:

NSURL(string:String, relativeTo:NSURL)

更好的方法是使用let docURL = NSURL(string:"RicFile.txt", relativeTo:directoryURL)

{{1}}

答案 1 :(得分:0)

随着对Swift语言的更新,对manager.URLForDirectory(...)的建议调用不再有效,因为调用可以抛出(异常)。具体错误是“Call可以抛出,但它没有标记为'try',并且没有处理错误”。可以使用以下代码处理throw:

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{

    if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)){
        [bottomRight mas_updateConstraints:^(MASConstraintMaker *make) {

            NSLog(@"We are on landscape");
            make.top.equalTo(upperRight.mas_bottom).with.offset(20);
            make.left.equalTo(self.view.mas_centerX).with.offset(20);
            make.right.equalTo(bottomRightRight.mas_left).with.offset(-20);
            make.bottom.equalTo(self.view.mas_bottom).with.offset(-100);

            make.width.equalTo(bottomRightRight);

        }]; }
    else {
        NSLog(@"Swapped");
        [bottomRight mas_updateConstraints:^(MASConstraintMaker *make) {

            make.top.equalTo(upperRight.mas_bottom).with.offset(200);
            make.left.equalTo(self.view.mas_centerX).with.offset(200);
            make.right.equalTo(bottomRightRight.mas_left).with.offset(-200);
            make.bottom.equalTo(self.view.mas_bottom).with.offset(-200);

            make.width.equalTo(bottomRightRight);

        }];

    }

}