2011-08-23 72 views
1

我試圖替換數組「第7行」的第7個索引。 NSMUTABLEARRAY「lines2」源自UNIX命令「ps aux」,我懷疑這個命令返回一個NSCFStrings數組。我現在基本上試圖用「Ss(Running)」代替「Ss」。問題是我每次都得到一個SIGABRT錯誤程序到達它試圖替換特定數組元素的那個部分。我的viewController的代碼如下。無法取代派生自「ps aux」輸出的NSArray UNIX命令

NSLog(@"myString is :%@", myString); 
int processID = [myString intValue]; 

NSTask *task; 
task = [[NSTask alloc] init]; 
[task setLaunchPath: @"/bin/ps"]; 

arguments = [NSArray arrayWithObjects: @"aux", [NSString stringWithFormat:@"%i", processID],nil]; 

[task setArguments: arguments]; 

NSPipe *pipe; 
pipe = [NSPipe pipe]; 
//[task setStandardOutput: pipe]; 
[task setStandardOutput:pipe]; 

NSFileHandle *file; 
file = [pipe fileHandleForReading]; 

[task launch]; 

NSData *data; 
data = [file readDataToEndOfFile]; 

NSString *string; 
string = [[NSString alloc] initWithData: data 
           encoding: NSUTF8StringEncoding]; 

// NSLog(@"%@",string); 


NSArray *lines= [string componentsSeparatedByString:@"\n"]; 

NSString *lastline = [lines objectAtIndex:[lines count]-2]; 
// NSLog(@"%@",lastline); 



lines2= [lastline componentsSeparatedByString:@" "]; 
NSLog(@"%@",lines2); 
for (int i=0; i<[lines2 count]; i++) { 

    if([[lines2 objectAtIndex:i] isEqualToString:@""]){ 
     [lines2 removeObjectAtIndex:i]; 
    } 

} 
for (int i=0; i<[lines2 count]; i++) { 

    if([[lines2 objectAtIndex:i] isEqualToString:@""]){ 
     [lines2 removeObjectAtIndex:i]; 
    } 

} 
for (int i=0; i<[lines2 count]; i++) { 

    if([[lines2 objectAtIndex:7] isEqualToString:@"Ss"]){ 
     [[lines2 objectAtIndex:0] replaceObjectAtIndex:7 withObject:@"SS (Running)"]; 

    } 
} 

任何幫助非常感謝!

回答

0

請查看方法-componentsSeparatedByString:的文檔。簽名是:

- (NSArray *)componentsSeparatedByString:(NSString *)separator 

請注意返回類型是NSArray。這是一個不可變的對象。你一定不能即使檢查返回的對象(比如用調試器或NSLog)顯示它實際上是可變的,也要更改它。您必須respect the API contract。 (閱讀題爲「接收可變對象」鏈接的部分。)

這就是說,你的錯誤的直接原因是這一行:

[[lines2 objectAtIndex:0] replaceObjectAtIndex:7 withObject:@"SS (Running)"]; 
^^^^^^^^^^^^^^^^^^^^^^^^ This is wrong 

lines2是一個字符串數組。 [lines2 objectAtIndex: 0]是一個字符串。你爲什麼要發送-replaceObjectAtIndex:withObject:呢?

0

你不說你看到的錯誤是什麼,但是你不能改變NSArray中的值,因爲NSArray是一個不可變的容器。

當您想要進行修改時,請使用NSMutableArray。如果你有一個NSArray已經(比如從-componentsSeparatedByString:的返回值),你可以這樣做,得到一個可變數組:

NSMutableArray * myMutableArray = [NSMutableArray arrayWithArray:lines2]; 
+0

其實它的一個NSMutableArray,我忘了提及。我認爲它拋出一個SIGABRT是因爲我試圖用一個NSString替換一個NSCFString(ps aux的輸出)。 –

0

NSArray不可變。首先將其複製到NSMutableArray(例如,使用[NSMutableArray arrayWithArray:]),以便操縱它。

在編譯期間沒有得到任何警告嗎?

+0

對不起,它應該是NSMutableArray,我輸錯了。它仍然拋出這個異常: –

+0

- [NSCFString replaceObjectAtIndex:withObject:]:無法識別的選擇器發送到實例0x4b25b70 2011-08-23 15:27:10.224 TableViewController_09 [3376:207]由於未捕獲的異常終止應用程序'NSInvalidArgumentException ',原因:' - [NSCFString replaceObjectAtIndex:withObject:]:無法識別的選擇發送到實例0x4b25b70' –