代码之家  ›  专栏  ›  技术社区  ›  Nick Veys

nsurl模拟到cfurlCreateCopyAppendingPathComponent?

  •  2
  • Nick Veys  · 技术社区  · 15 年前

    使用URL,更具体地说是从其他发现的URL增量构建它们。在这样做的过程中,我希望继续使用nsurl对象,而不是操作nsstring,只是为了从url类中获得附加的健全性检查和特定于url的方法。

    不幸的是,似乎没有办法让以下内容按我的意愿结合在一起:

    NSURL *base = [NSURL URLWithString:@"http://my.url/path"];
    NSString *suffix = @"sub/path";
    

    我想附加它们以获得:

    http://my.url/path/sub/path

    但我能得到的最好的结果是:

    NSURL *final = [NSURL URLWithString:suffix relativeToURL:base];
    

    它会修剪底部的路径,从而导致:

    http://my.url/sub/path

    有一个CoreFoundation函数可以做到:

    CFURLRef CFURLCreateCopyAppendingPathComponent (
       CFAllocatorRef allocator,
       CFURLRef url,
       CFStringRef pathComponent,
       Boolean isDirectory
    );
    

    这似乎很管用,但从objc到c的来回跳动是不和谐和烦人的…我宁愿操纵琴弦…我错过什么了吗?当然不是太挑剔了。:)

    4 回复  |  直到 11 年前
        1
  •  5
  •   Peter N Lewis    15 年前

    这是目标C-如果nsurl不做您需要的,请添加一个扩展类别。

    @interface NSURL ( Extensions )
    - (NSURL*) urlByAppendingPathComponent: (NSString*) component;
    @end
    
    @implementation NSURL ( Extensions )
    - (NSURL*) urlByAppendingPathComponent: (NSString*) component;
    {
        CFURLRef newURL = CFURLCreateCopyAppendingPathComponent( kCFAllocatorDefault, (CFURLRef)[self absoluteURL], (CFStringRef)component, [component hasSuffix:@"/"] );
        return [NSMakeCollectable(newURL) autorelease];
    }
    @end
    

    然后:

    *base = [NSURL URLWithString:@"http://my.url/path"];
    *suffix = @"sub/path";
    NSURL *final = [base urlByAppendingPathComponent:suffix];
    NSLog( @"%@", final );
    // displays http://my.url/path/sub/path
    
        2
  •  2
  •   benzado    13 年前

    从iOS 4.0开始,nsurl类提供了 URLByAppendingPathComponent: 方法。

        3
  •  1
  •   Tim    15 年前

    您可以将URL转换为字符串,附加相对组件,然后将其转换回URL:

    NSURL *base = [NSURL URLWithString:@"http://my.url/path"];
    NSString *suffix = @"/sub/path"; //Note that you need the initial forward slash
    
    NSString *newURLString = [[base absoluteString] stringByAppendingString:suffix];
    NSURL *newURL = [NSURL URLWithString:newURLString];

    边注: 如果URL恰好指向一个文件(不是在最初的示例中,但在某些情况下可能会有所帮助),则可以使用nsstring stringByAppendingPathComponent: 方法-这将使您无法为基本路径和相对路径选择正确的分隔符。

        4
  •  1
  •   xu huanze    11 年前

    我通过将斜线从相对URL的头部移动到基URL的末尾来修复此问题,如下所示:

    NSURL *base = [NSURL URLWithString:@"http://my.url/path/"]; //added a slash to the end
    NSString *suffix = @"sub/path"; //seems you don't have the leading slash in your sub path so you don't have to change this line