gpt4 book ai didi

iphone - 给定文件和目录生成相对路径的 Objective-C 代码

转载 作者:技术小花猫 更新时间:2023-10-29 10:43:25 25 4
gpt4 key购买 nike

给定一个文件路径和一个目录路径作为 NSStrings,有没有人有 Objective-C 代码来生成文件相对于目录的路径?

例如,给定目录 /tmp/foo 和文件 /tmp/bar/test.txt,代码应该生成 ../bar/test.txt.

我知道 Python,至少,有一个方法可以做到这一点:os.path.relpath .

最佳答案

与其继续为我为什么需要这个辩护,我决定只写它并分享。我基于 Python 的 os.path.relpathhttp://mail.python.org/pipermail/python-list/2009-August/1215220.html 的实现。

@implementation NSString (Paths)

- (NSString*)stringWithPathRelativeTo:(NSString*)anchorPath {
NSArray *pathComponents = [self pathComponents];
NSArray *anchorComponents = [anchorPath pathComponents];

NSInteger componentsInCommon = MIN([pathComponents count], [anchorComponents count]);
for (NSInteger i = 0, n = componentsInCommon; i < n; i++) {
if (![[pathComponents objectAtIndex:i] isEqualToString:[anchorComponents objectAtIndex:i]]) {
componentsInCommon = i;
break;
}
}

NSUInteger numberOfParentComponents = [anchorComponents count] - componentsInCommon;
NSUInteger numberOfPathComponents = [pathComponents count] - componentsInCommon;

NSMutableArray *relativeComponents = [NSMutableArray arrayWithCapacity:
numberOfParentComponents + numberOfPathComponents];
for (NSInteger i = 0; i < numberOfParentComponents; i++) {
[relativeComponents addObject:@".."];
}
[relativeComponents addObjectsFromArray:
[pathComponents subarrayWithRange:NSMakeRange(componentsInCommon, numberOfPathComponents)]];
return [NSString pathWithComponents:relativeComponents];
}

@end

请注意,在某些情况下这无法正确处理。它恰好可以处理我需要的所有情况。这是我用来验证正确性的简单单元测试:

@implementation NSStringPathsTests

- (void)testRelativePaths {
STAssertEqualObjects([@"/a" stringWithPathRelativeTo:@"/"], @"a", @"");
STAssertEqualObjects([@"a/b" stringWithPathRelativeTo:@"a"], @"b", @"");
STAssertEqualObjects([@"a/b/c" stringWithPathRelativeTo:@"a"], @"b/c", @"");
STAssertEqualObjects([@"a/b/c" stringWithPathRelativeTo:@"a/b"], @"c", @"");
STAssertEqualObjects([@"a/b/c" stringWithPathRelativeTo:@"a/d"], @"../b/c", @"");
STAssertEqualObjects([@"a/b/c" stringWithPathRelativeTo:@"a/d/e"], @"../../b/c", @"");
STAssertEqualObjects([@"/a/b/c" stringWithPathRelativeTo:@"/d/e/f"], @"../../../a/b/c", @"");
}

@end

关于iphone - 给定文件和目录生成相对路径的 Objective-C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6539273/

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