簡體   English   中英

將URL從NSString提取到NSMutableString

[英]Extracting URLs from NSString into NSMutableString

我有一個包含以下內容的文件:

cool name http://myurl1.tld/subdir/dir/var/ awesome\nanother cool name http://sub.domain.tld/dir/ nice\nsome nice name http://myname.tld/var/folder/ some\n 

我使用以下Objetive-C代碼讀取了文件:

NSData* data = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"../files/name.ext"]];
NSString* raw = [[NSString alloc]
                 initWithBytes:[data bytes]
                 length:[data length]
                 encoding:NSUTF8StringEncoding];

要從上述示例中提取所有URL,請使用:

NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray* matches = [detector matchesInString:raw options:0 range:NSMakeRange(0, [raw length])];

我的目標是將所有提取的URL附加到一個字符串中,並使用以下循環用分號(文件中沒有其他內容)將它們分開:

NSMutableString *allURLStrings = [NSMutableString string];
for (NSString *s in matches) {
    [allURLStrings appendString:s];
    [allURLStrings appendString:@";"];
 }

每當我嘗試運行代碼時,都會得到以下輸出:

以NSException(lldb)類型的未捕獲異常終止

我試圖使用這樣的循環,但是substringForCurrMatch僅包含一個斜杠(/):

NSMutableString * allRepoString = [NSMutableString string];  
for (NSTextCheckingResult *s in matches) {
        NSString* substringForCurrMatch = [s.URL path];
        [allRepoString appendString:substringForCurrMatch];
        [allRepoString appendString:@";"];
    }

當我在循環中檢查s時,會向我顯示正確的對象: s的內容

有沒有辦法使此代碼正常工作?

編輯完整的錯誤消息:

2016-08-11 23:00:19.272 AppName[34831:2892247] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[fetchurlsource allURLStrings]: unrecognized selector sent to instance 0x14c55ea00'
*** First throw call stack:
(0x181fa2db0 0x181607f80 0x181fa9c4c 0x181fa6bec 0x181ea4c5c 0x1000e8b6c 0x1000e8ee0 0x187100c40 0x187100844 0x18710759c 0x187104a88 0x18717afa4 0x1873a63ac 0x1873aa5f0 0x1873a7764 0x1839437ac 0x183943618 0x1839439c8 0x181f5909c 0x181f58b30 0x181f56830 0x181e80c50 0x18716f94c 0x18716a088 0x1000edb10 0x181a1e8b8)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

到目前為止,您發布的任何代碼都不會導致您發布的異常。

但是以下代碼不正確:

NSMutableString * allRepoString = [NSMutableString string];  
for (NSTextCheckingResult *s in matches) {
    NSString* substringForCurrMatch = [s.URL path];
    [allRepoString appendString:substringForCurrMatch];
    [allRepoString appendString:@";"];
}

您不想在s.URL上調用path方法。 要獲取完整的URL作為字符串,請使用absoluteString 這將為您提供URL作為字符串。 path只是為您提供URL的路徑部分。

NSMutableString * allRepoString = [NSMutableString string];  
for (NSTextCheckingResult *s in matches) {
    NSString* substringForCurrMatch = [s.URL absoluteString];
    [allRepoString appendString:substringForCurrMatch];
    [allRepoString appendString:@";"];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM