2012-03-01 15 views
-1

你好,我有一個問題,這個Objective-C的字符串問題

for (NSString* fileName in fileList){ 
    if ([fileName rangeOfString:@".png"].location != NSNotFound ) { 
     int x= col*130; 



     NSLog(@"add %@", fileName); 

     //create dynamically a nice thumbnail 
     UIImage* img = [UIImage imageWithContentsOfFile: 
         [self.documentsDir stringByAppendingPathComponent:fileName] 
         ]; 

     UIImageView* imgView = [[UIImageView alloc] initWithImage:img]; 
     imgView.frame = CGRectMake(0, 0, 110, 110); 
     imgView.contentMode = UIViewContentModeScaleAspectFill; 
     imgView.clipsToBounds = YES; 

     UIButton* imgBtn = [UIButton buttonWithType:UIButtonTypeCustom]; 
     [imgBtn addTarget:self action:@selector(imgPressed:) forControlEvents:UIControlEventTouchUpInside]; 
     imgBtn.frame = CGRectMake(x, row*130, 120, 120); 
     //imgBtn.backgroundColor = [UIColor lightGrayColor]; 
     [imgBtn addSubview:imgView]; 

     [self.canvas addSubview:imgBtn]; 

     [imgView release]; 


    col++; 
     if (x > 760) { 
      row++; 
      col = 0; 
     } 
    } 

這使得非常好的縮略圖,但我想只有特定名稱的文件,使之,所以我有問題如何只加載特定的名稱類型。像例如我有名爲... city1,city2,city3的圖像,都是png類型,我也有car1,car2 ....也是png。但是,一旦我想要只載入城市和唯一的一次汽車....

是否有可能只加載城市或僅汽車????

感謝所有。 我不知道如何對字符串進行精確比較。

我會用這樣的 如果(文件名isequaltoString:@ 「汽車%」)

,但它不工作.. =(

+0

這不是一個Xcode的問題,這是一個objec t-c問題。 – rooftop 2012-03-01 19:17:48

+0

真:)你不知道如何得到這個工作?:( – 2012-03-01 19:20:04

+1

看一看NSString的編程指南:https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/字符串/用品/ SearchingStrings.html#// apple_ref/DOC/UID/20000149-CJBBGBAI – gregheo 2012-03-01 19:21:36

回答

2

你已經有代碼來處理這個...

if ([fileName rangeOfString:@".png"].location != NSNotFound ) 

你只需要切ck for @「car」或者你正在尋找的任何東西,你不能只檢查位置屬性或者NSRange,因爲如果你在第一個字符索引0處匹配,你的上面的測試將會失敗。

返回值 一個NSRange結構,它給出接收者第一次出現aString時的位置和長度。如果未找到aString或爲空(@「」),則返回{NSNotFound,0}。

你應該檢查長度爲好。

+0

男人,用這個很棒!謝謝!!!! – 2012-03-01 19:33:10

+0

和一個小通知我無法檢查長度,因爲我可以在文檔目錄中擁有5e或數百個文件,如汽車。所以我無法檢查字符串的長度=)但是非常感謝=)完美的作品:) – 2012-03-01 19:34:20

+0

不是字符串的長度,NSRange的長度屬性。這會告訴你有多少個字符匹配。 – rooftop 2012-03-01 19:36:34

1

這可能工作:

NSString *word = @"car1.png"; 
if ([word rangeOfString:@"car"].location == NSNotFound) 
    NSLog(@"word does not contain car"); 
else 
    NSLog(@"word contains car"); 
+0

也感謝工作,豎起大拇指=) – 2012-03-01 19:35:07

+0

@rooftop'NSNotFound'等於'NSIntegerMax',不爲0,所以代碼將工作。 – Saphrosit 2012-03-01 19:38:31

+0

呸,@Saphrosit你是正確的,我看錯{NSNotFound,0}作爲NSNotFound == 0,而不是將其作爲位置,範圍。感謝您的更正。 – rooftop 2012-03-01 19:40:00

0

我會用這樣的事情,如果(文件名isequaltoString:@ 「汽車%」)

isEqualToString:

記住,文檔邪惡

然而,在你的情況下,我寧願使用hasPrefix:

+0

我知道文檔不是邪惡=) – 2012-03-01 19:45:13