2013-07-10 3 views
-1

파일 이름이 내 uitableview 인 코드가 있습니다. 그러나 한 번 파일을 삭제하고 새로 고침 오류가 나타납니다. 여기 내 파일 이름을 표시하려면 코드, 내 삭제 버튼 액션과 오류는 다음과 같습니다Objective-C : UITableView를 새로 고치는 방법?

나는 테이블에 파일 추가 할 때 작동이 코드를 실행 버튼을 누르면 첫째 때

-(IBAction)refresh{ 

    [[self mytable] reloadData]; 
} 

둘째, 테이블을 표시 할 값을 가져 와서 표시하는 코드입니다.

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
    if(!filePathsArray) 
    { 
     return 0; 
    } 
    if ([filePathsArray count] > 0) 
     return [filePathsArray count]; 
    else 
     return 0; 


} 

- -

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     //add code here for when you hit delete 
     NSString *currentFileName = filePathsArray[indexPath.row]; 
     NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) objectAtIndex:0]; 
     NSString *filePath = [documentsDirectoryPath stringByAppendingPathComponent:currentFileName]; 
     fileURL = [NSURL fileURLWithPath:filePath]; 
     NSLog(@"urlstring %@",fileURL); 
     NSFileManager *fileManager = [NSFileManager defaultManager]; 
     [fileManager removeItemAtPath:filePath error:NULL]; 
     NSLog(@"successfully deleted"); 

    } 
} 

-

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell"]; 
    } 


    NSLog(@"urlstring %@",[filePathsArray objectAtIndex:indexPath.row]); 


    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil]; 

    cell.textLabel.text = [filePathsArray[indexPath.row] lastPathComponent]; 
filePathsArray = [[NSArray alloc] initWithArray: [[[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil]mutableCopy]]; 
    return cell; 
} 

-

,536,913

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    filePathsArray = [[[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil]mutableCopy]; 


    mytable.dataSource = self; 
    mytable.delegate = self; 



} 

: 삭제 및 업데이트가 발생할 때까지이 잘 작동합니다 63,210

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 
    return 1; 

} 

내가받을 오류는 이것이다 :

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 6 beyond bounds [0 .. 5]' 
*** First throw call stack: 
(0x2049012 0x1473e7e 0x1ffeb44 0x3c3a 0x69b8fb 0x69b9cf 0x6841bb 0x694b4b 0x6312dd 0x14876b0 0x2c84fc0 0x2c7933c 0x2c79150 0x2bf70bc 0x2bf8227 0x2bf88e2 0x2011afe 0x2011a3d 0x1fef7c2 0x1feef44 0x1feee1b 0x23dc7e3 0x23dc668 0x5e0ffc 0x2212 0x2145) 
libc++abi.dylib: terminate called throwing an exception 
(lldb) 

내가 인해이 오류가 나타날 수

NSLog(@"urlstring %@",[filePathsArray objectAtIndex:indexPath.row]); 

하지만 한 번이 문제가 다음 라인으로 말한다 제거. 아무도 도와 줄 수 있니? 추가 tableView:commitEditingStyle:에서이 코드 filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];

:

[filePathsArray removeObjectAtIndex:indexPath.row]; 

이것은 당신이 (당신이 테이블 뷰를 채우는 데 사용하는 데이터의 무결성을 그렇게 유지해야을 tableView:cellForRowAtIndexPath:에서

+4

'numberOfRowsInSection :'의 구현을 좋아합니다. 'return filePathsArray.count; '대신에, 당신을 보호하지 못하는 불필요하고 중복 된 검사를 두 번하고 있습니다. 가독성을 떨어 뜨리고 코드를 파헤 치려고하는 사람을 혼란에 빠뜨립니다. –

+2

@ H2CO3 감각적 인 조언을 비난적인 의견으로 바꾸는 방법을 "사랑"합니다. – herzbube

+1

@herzbube 너무 좋아합니다. 그것은 특별한 힘입니다. –

답변

2

filePathsArray에서 데이터를 설정하는 방식 때문에 tableView가 필요한 것보다 더 많은 셀을 렌더링합니다.

파일을 삭제 한 후 filePathsArray를 업데이트하십시오.

어떻게하면 commitEditingStyle 메서드에서 파일을 삭제하지만 filePathsArray 개체를 업데이트하여 해당 파일의 하위 경로를 제거하지 않아도됩니다.

  1. 일예 : 당신이 filePathsArray를 업데이트

    유일한 장소는numberOfRowsInSection

    그래서 기본적으로

    라고하는 cellForRowAtIndexPath에 filePathsArray는 6 개의 파일에 대한 하위 경로를 포함합니다.

  2. commitEditingStyle에서 파일을 삭제하지만 filePathsArray (여전히 6 개의 하위 경로를 포함)는 업데이트하지 않습니다.
  3. 당신은 ... 당신의 jQuery과에 표시되는 세포의 수를 얻기 위해 호출이 반환 이제 모든 호출됩니다 여전히 6.
  4. cellForRowAtIndexPath이다 filePathsArray 수를] reloadData
  5. numberOfRowsInSection에있는 버튼을 누르면 열.
  6. 위의 메서드 내에서 filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];을 호출하면 삭제 된 파일로 인해 filePathsArray에 5 개의 개체가 생깁니다.
  7. 하지만 .... 당신의 UITableView는 이미 이전 filePathsArray 수에 대해 6 개의 행을 렌더링하기 시작했습니다.
  8. 이제 셀 번호 6 (indexPath.row = 5)을 렌더링하면 cell.textLabel.text = [filePathsArray[indexPath.row] lastPathComponent];이 호출되고 배열의 마지막 인덱스는 4가됩니다. 이로 인해 충돌이 발생합니다.

commitEditingStylefilePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];을 입력하면 오류가 중지됩니다.

또한 데이터 소스 개체를 cellForRowAtIndexPath에서 수정하지 마십시오. 어레이가 현재 commitEditingStyle에서 업데이트되고 있으므로 filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil]; 콜을 꺼내십시오.

+1

정말 고마워요. – user2569812

1

,이 코드를 제거 테이블이 그것에 대해 모를 때 항목의 수를 변경하지 말고 테이블에 있다고 생각할 때 변경하십시오.

+0

^동의 ... 내 생각은 정확하게. – Sid

관련 문제