-1

每次进入 UITableView 时,我都想向我的数组中添加一个新对象。问题是当我从这个视图出去时 UITableView 会被释放,所以我不能在 UITableView 类中声明我的数组。

我创建了一个名为“array”的新 NSObject 类,但我不知道如何使用它。

数组.h

#import <Foundation/Foundation.h>

@interface Array : NSObject
{
    NSMutableArray *tableau;
}

@property (strong) NSMutableArray* tableau;
- (id)initWithName:(NSMutableArray *)atableau  ;

- (NSMutableArray*) tableau;

- (void) setTableau:(NSMutableArray*) newTableau;

+(Tableau*)instance;

@end

数组.m

#import "Array.h"

@implementation Array

- (id)initWithName:(NSMutableArray *)atableau {
    if ((self = [super init]))

    {
        self.tableau = atableau;
    }
    return self;

}

- (NSMutableArray*) tableau{
    return tableau;
}

- (void) setTableau:(NSMutableArray*) newTableau{
    tableau = newTableau;
}

+(Tableau*)instance{
    static dispatch_once_t once;
    static Array *sharedInstance;
    dispatch_once(&once, ^{
        sharedInstance = [[self alloc] initWithName:@"jean" ];
    });
    return sharedInstance;
}
@end

UITableViewController.m

...
- (void)viewDidAppear:(BOOL)animated
{
    if (![[Array instance] tableau]) {

    }
    [[[Array instance]tableau]addObject:@"koko"];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    NSLog(@"appear");

}

...

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [[[Array instance] tableau] 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.
    }
...

当我这样做时,我得到了这个错误:

'NSInvalidArgumentException',原因:'-[__NSCFConstantString addObject:]:无法识别的选择器发送到实例 0x5aa4'

感谢您未来的回复。

4

1 回答 1

1

这行代码中的问题:

sharedInstance = [[self alloc] initWithName:@"jean" ];

结果你分配NSString实例而不是NSMutableArray

- (id)initWithName:(NSMutableArray *)atableau {
    self = [super init];
    if (self) {
       self.tableau = atableau;
    }
    return self;
}

将其更改为:

sharedInstance = [[self alloc] initWithName:[[NSMutableArray alloc] initWithObjects:@"jean", nil]];
于 2013-11-12T11:48:15.417 回答