gpt4 book ai didi

ios - NSURL 类似于 CFURLCreateCopyAppendingPathComponent?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:00:21 27 4
gpt4 key购买 nike

使用 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 来回跳动是不和谐和烦人的......我宁愿只是操纵字符串......我错过了什么吗?当然除了太挑剔。 :)

最佳答案

这是 Objective 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

关于ios - NSURL 类似于 CFURLCreateCopyAppendingPathComponent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1036547/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com