2012-08-08 2 views
-1

테이블에 개체를 삽입 할 수 있지만 추가 단추를 누를 때마다 캐치되지 않는 예외로 인해 충돌이 발생합니다. 그것은 NSMutableArray 및 내 테이블 관련 문제

Attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update 

여기 내 모든 테이블에 물건을 처리하는 내 기본보기 컨트롤러 ... 말한다

#import "MasterViewController.h" 

#import "DetailViewController.h" 

#define kFileName  @"steakNames.plist" 

@interface MasterViewController() { 
    NSMutableArray *_objects; 
} 
@end 

@implementation MasterViewController 

@synthesize steakName; 

- (NSString *)dataFilePath { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    return [documentsDirectory stringByAppendingPathComponent:kFileName]; 
} 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     self.title = NSLocalizedString(@"Master", @"Master"); 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    NSString *filePath = [self dataFilePath]; 
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { 
     _objects = [[NSMutableArray alloc] initWithContentsOfFile:filePath]; 
    } 

    UIApplication *app = [UIApplication sharedApplication]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app]; 

    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    self.navigationItem.leftBarButtonItem = self.editButtonItem; 

    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)]; 
    self.navigationItem.rightBarButtonItem = addButton; 
} 

- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); 
} 

- (void)insertNewObject:(id)sender 
{ 
    if (!steakName) { 
     steakName = @"No name"; 
    } 
    [_objects insertObject:[self steakName] atIndex:0]; 

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 

    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; 
} 

#pragma mark - Table View 

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return _objects.count; 
} 

// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
     cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    } 


    NSDate *object = [_objects objectAtIndex:indexPath.row]; 
    cell.textLabel.text = [object description]; 
    return cell; 
} 

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Return NO if you do not want the specified item to be editable. 
    return YES; 
} 

- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     [_objects removeObjectAtIndex:indexPath.row]; 
     [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    } else if (editingStyle == UITableViewCellEditingStyleInsert) { 
     // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. 
    } 
} 

/* 
// Override to support rearranging the table view. 
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath 
{ 
} 
*/ 

/* 
// Override to support conditional rearranging of the table view. 
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Return NO if you do not want the item to be re-orderable. 
    return YES; 
} 
*/ 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (!self.detailViewController) { 
     self.detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil]; 
    } 
    NSDate *object = [_objects objectAtIndex:indexPath.row]; 
    self.detailViewController.detailItem = object; 
    [self.navigationController pushViewController:self.detailViewController animated:YES]; 
} 

- (void)applicationWillResignActive:(NSNotification *)notification { 
    [_objects writeToFile:[self dataFilePath] atomically:YES]; 
} 
@end 
+0

'numberofSectionsInTableView'도 재정의 했습니까? 추가 버튼을 눌렀을 때 일어나는 일에 대한 코드를 게시 할 수 있습니까? –

+0

추가하려는 코드는 어디에 있습니까? –

+0

@ DanF 나는 거기에 넣었다. 1로 설정했다. –

답변

0

대부분의 경우 오류의 원인이 반환 0 :

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 

    return ...; 
} 

먼저 필요한 모든 메서드를 사용하여 테이블 뷰의 전체 예제를 가져 와서 시작하는 것이 좋습니다.

일반적으로 이러한 메소드를 구현해야합니다

  • (NSInteger) numberOfSectionsInTableView : (jQuery과 *)있는 tableView

  • (있는 NSString *)있는 tableView : (jQuery과 *)있는 tableView titleForHeaderInSection : (NSInteger) 섹션

  • (NSInteger)를 tableView (jQuery과 *)를 tableView numberOfRowsInSection (NSInteger) 섹션

  • (있는 UITableViewCell *)를 tableView (jQuery과 *)를 tableView cellForRowAtIndexPath (NSIndexPath *) indexPath

  • (공극)를 tableView (jQuery과 *)를 tableView didSelectRowAtIndexPath (NSIndexPath *) indexPath

그래서 NSMutableArray에 아무런 문제가 없다면 어쨌든 배열에 아직 객체 수가 없다면 객체를 인덱스에 삽입 할 수 없습니다. 예를 들어 인덱스 4에 삽입하지만 배열에는 객체가 2 개뿐입니다. 항상 NSMutableArray에 객체를 추가하고이 배열에있는 객체의 수를 늘릴 수 있습니다.

+0

내 질문을 읽었습니까? 나는 특별히 거기에 있다고 말했습니다. –

+0

이 메소드가 반환하는 것을 확인 했습니까? 추가 버튼은 정확히 무엇을합니까? 문제는 여기에 표시되지 않는 코드에 있습니다! – user387184

+0

메인 포스트를 업데이트했습니다. 미안하지만 충분히 미안합니다. –