删除UICollectionView单元格时出现NSRangeException

时间:2015-01-28 07:09:29

标签: objective-c uicollectionview nsrangeexception

我尝试从UICollectionView循环中的for.. in中删除单元格,并且每次获取NSRangeException时都是如此。我无法理解为什么会发生这种情况,因为我首先对数组进行排序,然后尝试删除。所以问题是我首先尝试向服务器发送请求,并且只有在响应成功时才会移除UICollectionView单元格和数组元素。这是我的代码:

通过循环传递元素:

- (IBAction)deletePictures:(id)sender {
int i = 0;
if (selectedPhotosURL.count>0){
    loadCount = (int)selectedPhotosURL.count;
//sorting an array (it works fine)
    NSArray *indexPaths = sortMediaCollection.indexPathsForSelectedItems;
    NSMutableArray *pathes = [NSMutableArray arrayWithArray:indexPaths];
    NSSortDescriptor *highestToLowest = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO];
    [pathes sortUsingDescriptors:[NSArray arrayWithObject:highestToLowest]];
    [selecedCellsArray sortUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
        return [str2 compare:str1 options:(NSNumericSearch)];
    }];


    NSLog(@"selectedCElls %@",selecedCellsArray);
    for(NSIndexPath *indexPath in pathes) {
        NSLog(@"indexPath in pathes is %ld",(long)indexPath.row);
        AVMSMCell *cell = (AVMSMCell *)[sortMediaCollection cellForItemAtIndexPath:indexPath];
        AVMDataStore *oneItem = [smArray objectAtIndex:indexPath.row];
        NSString *contentId = oneItem.fileId;
        if (i<selectedPhotosURL.count){
            NSLog(@"indexPath second loop is %ld",(long)indexPath.row);
            [self deleteUserPhotos:contentId : indexPath.row : cell]; // send request to the server it's ok too.
            i++;
        }
    }

} else {
    [self selectAtLeastOneFirst];
  }

}

例如,我在这里选择了6个单元格,我的数组从右到上依次排列(5,4,3,2,1,0)。然后我用这个顺序在方法中传递这些元素。

请求发送方式:

-(void)deleteUserPhotos : (NSString *)contentId : (NSInteger )pathRow : (AVMSMCell *) cell{
NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:(unsigned int)pathRow];
if (([selecedCellsArray containsObject:[NSString stringWithFormat:@"%@",rowNsNum]]) ) 
{
    cell.selectedBG.backgroundColor = DANGER;
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *token = [defaults objectForKey:@"token"];
    NSString *header = [NSString stringWithFormat:@"Bearer %@",token];
    NSDictionary *params = @{@"lang": @"en",@"content_id":contentId,@"project_id":[defaults objectForKey:@"project_id"]}; 
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"Authorization"];
    [manager POST:@"http://example.com/api/project/delete-content" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        NSLog(@"JSON: %@", responseObject);

        if ([[responseObject objectForKey:@"result"] isEqualToString:@"success"]){
            @try{
                NSLog(@"pathRow in TRY %ld",(long)pathRow); // HERE I get wrong number after two or three elements already passed
                [smArray removeObjectAtIndex:(unsigned int)pathRow];

                [selecedCellsArray removeObject:[NSString stringWithFormat:@"%ld",(long)pathRow]];

                cell.selectedBG.hidden = YES;
                [sortMediaCollection reloadSections:[NSIndexSet indexSetWithIndex:0]];
                loadCount--;

                }
            } @catch (NSException *e){
                NSLog(@"something is bad %@",e);
                [SVProgressHUD dismiss];
                if (smArray.count<pathRow-1){
                [smArray removeObjectAtIndex:(unsigned int)pathRow-1];
                } 
            } @finally {
                cell.selectedBG.hidden = YES;
                [sortMediaCollection reloadSections:[NSIndexSet indexSetWithIndex:0]];
            }
        } else {
            NSLog(@"can't delete photo!");
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        NSLog(@"Error: %@", error);
        errorEndSpinner
    }];
    }
}

所以在上面的方法中,我已经传递了两个或三个元素后得到错误的元素编号,即frist元素是5,然后是4,然后 2 3 ,1,0 。 此时我的@catch处理异常并尝试使用[smArray removeObjectAtIndex:(unsigned int)pathRow-1];删除元素,然后我得到NSRangeException并且我的应用崩溃了。我做错了什么?

2 个答案:

答案 0 :(得分:0)

我用this回答解决了我的问题并且稍微修改了我的代码。 我有一个NSRangeException,因为我通过循环删除了UICollectionView个项目。相反,我应该更好地使用多个删除像这样:

    // Delete the items from the data source.
                    [self deleteItemsFromDataSourceAtIndexPaths:selectedItemsIndexPaths];

                        // Now delete the items from the collection view.
                    [sortMediaCollection deleteItemsAtIndexPaths:selectedItemsIndexPaths];

所以现在我的代码看起来像:

通过循环:

- (IBAction)deletePictures:(id)sender {
int i = 0;
if (selectedPhotosURL.count>0){
    [SVProgressHUD showWithStatus:@"Deleting" maskType:SVProgressHUDMaskTypeBlack];
    loadCount = (int)selectedPhotosURL.count;
    NSArray *indexPaths = sortMediaCollection.indexPathsForSelectedItems;
    NSMutableArray *pathes = [NSMutableArray arrayWithArray:indexPaths];
    NSSortDescriptor *highestToLowest = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO];
    [pathes sortUsingDescriptors:[NSArray arrayWithObject:highestToLowest]];
    [selecedCellsArray sortUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
        return [str2 compare:str1 options:(NSNumericSearch)];
    }];

    for(NSIndexPath *indexPath in pathes) {
        AVMSMCell *cell = (AVMSMCell *)[sortMediaCollection cellForItemAtIndexPath:indexPath];
        AVMDataStore *oneItem = [smArray objectAtIndex:indexPath.row];
        NSString *contentId = oneItem.fileId;
        if (i<selectedPhotosURL.count){
            [self deleteUserPhotos:contentId : indexPath.row : cell pathes:pathes]; //pass array with pathes into 'deleteUserPhotos'
            i++;
        }
    }

} else {
    [self selectAtLeastOneFirst];
   }

}

主要方法:

-(void)deleteItemsFromDataSourceAtIndexPaths:(NSArray  *)itemPaths {
NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
for (NSIndexPath *itemPath  in itemPaths) {
    [indexSet addIndex:itemPath.row];
}
[smArray removeObjectsAtIndexes:indexSet];
}

-(void)deleteUserPhotos : (NSString *)contentId : (NSInteger )pathRow : (AVMSMCell *) cell pathes:(NSMutableArray*)selectedItemsIndexPaths{
NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:(unsigned int)pathRow];
if (([selecedCellsArray containsObject:[NSString stringWithFormat:@"%@",rowNsNum]]))
{
    cell.selectedBG.backgroundColor = DANGER;
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *token = [defaults objectForKey:@"token"];
    NSString *header = [NSString stringWithFormat:@"Bearer %@",token];
    NSDictionary *params = @{@"lang": @"en",@"content_id":contentId,@"project_id":[defaults objectForKey:@"project_id"]}; 
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"Authorization"];
    [manager POST:@"http://example.com/api/project/delete-content" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        NSLog(@"JSON: %@", responseObject);

        if ([[responseObject objectForKey:@"result"] isEqualToString:@"success"]){
            @try{

                [selecedCellsArray removeObject:[NSString stringWithFormat:@"%ld",(long)pathRow]];

                loadCount--;

                if (loadCount==0){ //only there remove items from collectionview

                        // Delete the items from the data source.
                    [self deleteItemsFromDataSourceAtIndexPaths:selectedItemsIndexPaths];
                        // Now delete the items from the collection view.
                    [sortMediaCollection deleteItemsAtIndexPaths:selectedItemsIndexPaths];

                    [selectedPhotosURL removeAllObjects];
                    }
            } @catch (NSException *e){
                NSLog(@"something is bad %@",e);
                [SVProgressHUD dismiss];
                if (smArray.count<pathRow-1){
                [smArray removeObjectAtIndex:(unsigned int)pathRow-1];
                }
            } @finally {
                cell.selectedBG.hidden = YES;
                [sortMediaCollection reloadSections:[NSIndexSet indexSetWithIndex:0]];
            }
        } else {
            NSLog(@"can't delete photo!");
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        NSLog(@"Error: %@", error);
        errorEndSpinner
    }];
  }
}

希望这会对某人有所帮助。

答案 1 :(得分:0)

我遇到了同样的错误,但发现它与另一个拥有该数组的镜像副本的类有关,并且该类访问了已删除的索引。

您可以添加异常断点以查看异常的确切位置。用于区分代码中的错误和来自iOS SDK的错误:NSRangeException when deleting last UICollectionViewCell