将字符串数据添加到NSMutableArray

时间:2013-05-24 10:48:22

标签: ios nsstring nsmutablearray

我有一个NSString,每次单击一个单元格时都会获取一个新值我想将此值添加到NSMutableArray中,我尝试了以下[NSMutableArray addObject:NSString]但是这会在第一个索引值处添加字符串NSMutableArray并单击下一个单元格,它将替换先前存储的值。我想保存所有值。怎么办呢?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


 UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];

NSIndexPath *tableSelection = [listingSet indexPathForSelectedRow];

if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
    cell.accessoryType = UITableViewCellAccessoryNone;

    [SelectedFiles removeObject:ID];
    NSLog(@"++++++Titlesss %@",SelectedFiles);



    [listingSet deselectRowAtIndexPath:tableSelection animated:YES];
} else { 

    cell.accessoryType = UITableViewCellAccessoryCheckmark;

          ID = [NSString stringWithFormat:@"%@",[[ParsedData valueForKey:@"ID"]objectAtIndex:indexPath.row]];

                   [SelectedFiles insertObject:ID atIndex:0];
    NSLog(@"%@",ID);
        NSLog(@"%@",SelectedFiles);







            [listingSet deselectRowAtIndexPath:tableSelection animated:YES];
}

}

这似乎不起作用。

编辑:我在某处读到我的数据正在保存在数组的第一个索引上,因此每次我保存数据时我都需要增加数组的索引路径,但我无法弄清楚如何。

3 个答案:

答案 0 :(得分:2)

看起来你每次都在创建一个新阵列。你不应该这样做。尝试使您的数组成为视图控制器的属性。

@property (nonatomic, strong) NSMutableArray *stringElements;

在视图控制器的init方法中:

self.stringElements = [@[] mutableCopy];

当点击一个单元格时:

NSString *ID = [NSString stringWithFormat:@"%@", [[ParsedData 
valueForKey:@"ID"]objectAtIndex:indexPath.row]];
[self.stringElements addObject: ID];

答案 1 :(得分:1)

NSMutableArray *FileID = [[NSMutableArray alloc]init];

或使用

   NSMutableArray *FileID = [[NSMutableArray alloc]initWithCapacity:3];

将其删除范围。此行初始化并为数组提供新的有效内存,每次执行时都会创建数组。因此添加的对象始终保留在新数组的第1个位置从上面提到的这条线形成。

所以解决方案只是将此行移出声明的位置。将其放在initviewdidLoadviewWillAppear方法中,就是这样。

addObject:方法将对象添加到NSMutableArray中的下一个可用位置,这样就足够了

制作一个实例变量

@interface ATTDownloadPage ()
{
    NSMutableArray * FileID;
}

- (void)viewDidLoad
{
    NSMutableArray *FileID = [[NSMutableArray alloc]initWithCapacity:3];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *ID = [NSString stringWithFormat:@"%@", [[ParsedData valueForKey:@"ID"]objectAtIndex:indexPath.row]];
    [FileID addObject:ID];
}

修改 来自您的代码

    [SelectedFiles insertObject:ID atIndex:0];

导致问题 .t此行一直替换索引0处的对象,因此没有值添加到数组中 试试这个代替上面的代码

 NSMutableArray *tempArray =[[NSMutableArray alloc]initWithCapacity:3];
        [tempArray addObject:ID];
        [tempArray addObjectsFromArray:SelectedFiles];
        SelectedFiles =[NSMutableArray arrayWithArray:tempArray];

答案 2 :(得分:0)

使用此行,您每次都会创建一个新数组。

NSMutableArray *FileID = [[NSMutableArray alloc]init];