用于UITableViewController的单例NSArray对象

时间:2013-11-12 09:13:11

标签: ios objective-c arrays

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

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

  

Array.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
  

Array.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'

感谢您将来的回复。

1 个答案:

答案 0 :(得分: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]];