NSMutableArray不存储任何对象

时间:2011-12-12 16:17:13

标签: ios xcode nsmutablearray

我的NSMutableArray不存储任何对象,无论是String还是复杂类。我试着将ind init和init分配为数组。两者都没有成功。

.m文件:

@interface WorkCentersViewController()
@property (nonatomic, retain) NSMutableArray *selectedWorkCenters;
@end


@implementation WorkCentersViewController
@synthesize selectedWorkCenters;


-(id)init{

    self = [super init];

    if(self){


        //self.selectedWorkCenters = [[NSMutableArray alloc] init]; //doesn't work too
        self.selectedWorkCenters = [NSMutableArray array];

    }
    return self;
}

- (void)dealloc
{
    [selectedWorkCenters release];
    [super dealloc];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if(cell.accessoryType == UITableViewCellAccessoryCheckmark){      
        ...
    }else{
        //select
        cell.accessoryType = UITableViewCellAccessoryCheckmark; 
        //add
        [self.selectedWorkCenters addObject:[self.workCenters objectAtIndex:indexPath.row]];
        NSLog(@"Sel WC Count: %d", [self.selectedWorkCenters count]); //always 0
    }
}

为什么不存储WorkCenter的对象?我做错了什么?

BR, mybecks

5 个答案:

答案 0 :(得分:1)

也许没有调用特定的init方法?这是一个UITableViewController吗?也许你用initWithStyle:初始化它?我会在你初始化数组的行上设置一个断点来检查。

答案 1 :(得分:0)

-initWithNibName:bundle:UIViewController指定的初始值设定项,因此任何初始化代码都应该显示在该方法的覆盖中。如果此 UITableViewController的子类,那么标记是正确的,initWithStyle是放置它的好地方。

此外,通常,viewDidLoad / viewDidUnload为您提供了查看所需的分配/取消分配数据结构的好地方,但如果需要,可以重新创建。

答案 2 :(得分:0)

尝试以这种方式初始化NSMutableArray:

self.selectedWorkCenters = [[NSMutableArray alloc] init];

答案 3 :(得分:0)

好的,这是我的想法。在您的初始化中,您正在使用:

// This one is wrong, you are [NSMutableArray array] returns a NSArray which cannot be 
// mutated so you cannot add objects to it. That is why it is not working.
//
self.selectedWorkCenters = [NSMutableArray array];

// This one is wrong because you have a leak here (Although it should work)
//
self.selectedWorkCenters = [[NSMutableArray alloc] init];

试试这个:

selectedWorkCenters = [[NSMutableArray alloc] init];

并将其放在 viewDidLoad 方法中。希望能帮助到你。让我知道:)

答案 4 :(得分:0)

我发现了错误。

在另一种方法中我有作业

selectedWorkCenters = availableWorkCenters;

availableWorkCenters未初始化 - 在调试器屏幕中始终为0x0。

相关问题