iPhone: добавление строк в UITableView без массивов - PullRequest
0 голосов
/ 20 мая 2011

Дано:

Я создал Navigation-based Application для Obj-C iPhone.В методе - (void) viewDidLoad в файл RootViewController.m добавлена ​​кнопка +:

 / * Create the button that appears on the Right Side * /
 UIBarButtonItem * rightButton =
 [[UIBarButtonItem alloc]
  initWithBarButtonSystemItem: UIBarButtonSystemItemAdd
  target: self
  action: @ selector (performRight:)];

 / * Assign the buttons to the Navigation Item's properties * /
 self.navigationItem.rightBarButtonItem = rightButton;

 [rightButton release];

В методе - (NSInteger) tableView: (UITableView *) tableView numberOfRowsInSection: (NSInteger) section изменено возвращаемое значение с 1 на 4:

return 4;

Метод - (void) performRight: (id) paramSender

- (Void) performRight: (id) paramSender
{
     / * Perform another action here * /


     // Add a row (?).

}

Вопрос:

Как добавить строку в таблицу, когда янажмите на кнопку +?

Объяснение:

Все я нашел примеры с использованием массивов, которые я делаю не нужно.

Спасибо.


Это код по умолчанию.В сообщении выше я написал полный процесс создания приложения.

// 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] autorelease];
    }

    // Configure the cell.
    return cell;
}

Я добавил этот код

[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:row inSection:section]] withRowAnimation:UITableViewRowAnimationBottom];

Но я получаю ошибку Thread 1: Program received signal "SIGABRT".Я цитирую ниже NSLog:

2011-05-21 08:17:24.932 MyTable[2981:207] *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-1448.89/UITableView.m:995
2011-05-21 08:17:24.948 MyTable[2981:207] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (4) must be equal to the number of rows contained in that section before the update (4), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted).'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x00dc15a9 __exceptionPreprocess + 185
    1   libobjc.A.dylib                     0x00f15313 objc_exception_throw + 44
    2   CoreFoundation                      0x00d79ef8 +[NSException raise:format:arguments:] + 136
    3   Foundation                          0x008163bb -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 116
    4   UIKit                               0x00091e8b -[UITableView(_UITableViewPrivate) _endCellAnimationsWithContext:] + 8420
    5   UIKit                               0x000811e8 -[UITableView endUpdates] + 42
    6   MyTable                             0x00003229 -[RootViewController performRight:] + 313
    7   UIKit                               0x000134fd -[UIApplication sendAction:to:from:forEvent:] + 119
    8   UIKit                               0x00225cc3 -[UIBarButtonItem(UIInternal) _sendAction:withEvent:] + 156
    9   UIKit                               0x000134fd -[UIApplication sendAction:to:from:forEvent:] + 119
    10  UIKit                               0x000a3799 -[UIControl sendAction:to:forEvent:] + 67
    11  UIKit                               0x000a5c2b -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
    12  UIKit                               0x000a47d8 -[UIControl touchesEnded:withEvent:] + 458
    13  UIKit                               0x00037ded -[UIWindow _sendTouchesForEvent:] + 567
    14  UIKit                               0x00018c37 -[UIApplication sendEvent:] + 447
    15  UIKit                               0x0001df2e _UIApplicationHandleEvent + 7576
    16  GraphicsServices                    0x00ffa992 PurpleEventCallback + 1550
    17  CoreFoundation                      0x00da2944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
    18  CoreFoundation                      0x00d02cf7 __CFRunLoopDoSource1 + 215
    19  CoreFoundation                      0x00cfff83 __CFRunLoopRun + 979
    20  CoreFoundation                      0x00cff840 CFRunLoopRunSpecific + 208
    21  CoreFoundation                      0x00cff761 CFRunLoopRunInMode + 97
    22  GraphicsServices                    0x00ff91c4 GSEventRunModal + 217
    23  GraphicsServices                    0x00ff9289 GSEventRun + 115
    24  UIKit                               0x00021c93 UIApplicationMain + 1160
    25  MyTable                             0x00002979 main + 121
    26  MyTable                             0x000028f5 start + 53
    27  ???                                 0x00000001 0x0 + 1
)
terminate called after throwing an instance of 'NSException'
sharedlibrary apply-load-rules all
Current language:  auto; currently objective-c

Какие данные вы представляете, которые не нуждаются в массиве?- Дипак 7 часов назад

Это пример приложения, которое должно работать на курсах iOS Developer.

Ответы [ 2 ]

1 голос
/ 28 мая 2011

Решение!

В RootViewController.h добавить

@ interface RootViewController:
UITableViewController {
     int rows; }

В RootViewController.m добавить

 - (NSInteger) tableView: (UITableView *) tableView numberOfRowsInSection: (NSInteger) section {
      return rows; }

и

 - (Void) performRight: (id) paramSender

 {
      // Insert a row
      ++rows;
      [self.tableView reloadData]; }

В RootViewController.xib добавить торговые точки

 tableView - Table View

Спасибо всем за поддержку!

0 голосов
/ 20 мая 2011
- (Void) performRight: (id) paramSender
{
    / * Perform another action here * /

    int section = 0;

    // insert at top
    int row = 0;
    // or insert at bottom
    //int row = [self tableView:tableView numberOfRowsInSection:section];

    [self.tableView beginUpdates];
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject[NSIndexPath indexPathForRow:row inSection:section]]
                          withRowAnimation:UITableViewRowAnimationBottom];
    [self.tableView endUpdates];

    [self.tableView reloadData];
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...