为什么我得到:“mutating method sent to immutable object”当尝试从MutableArray中删除? [英] Why am I getting : "mutating method sent to immutable object" when trying remove from MutableArray?

查看:191
本文介绍了为什么我得到:“mutating method sent to immutable object”当尝试从MutableArray中删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚为什么我在这段代码中得到mutate method sent to immutable object。数组必须以某种方式不可变,但我不知道为什么。

I can't figure out why I am getting the 'mutating method sent to immutable object' in this piece of code. The array must be immutable somehow but I don't know why.

接口:

    @interface SectionsViewController : UIViewController<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate> {

    UITableView *table;
    UISearchBar *search;
    NSMutableDictionary *names;
    NSMutableArray *keys;

}
@property (nonatomic, retain) IBOutlet UITableView *table;
@property (nonatomic, retain) IBOutlet UISearchBar *search;
@property (nonatomic, retain) NSDictionary *allNames;
@property (nonatomic, retain) NSMutableDictionary *names;
@property (nonatomic, retain) NSMutableArray *keys;

-(void) resetSearch;
-(void) handleSearchForTerm:(NSString *)searchTerm;

@end

请注意,名称是MutableDictionary。

Notice that names is a MutableDictionary.

下面一行是抛出异常

[array removeObjectsInArray:toRemove];

这里是完整上下文中的方法:

Here the method in full context:

-(void)handleSearchForTerm:(NSString *)searchTerm
{
    NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];
    for(NSString *key in self.keys)
    {
        NSMutableArray *array = [names valueForKey:key];
        NSMutableArray *toRemove = [[NSMutableArray alloc] init];

        for(NSString *name in array)
        {
            if([name rangeOfString:searchTerm
                           options:NSCaseInsensitiveSearch].location == NSNotFound)
                [toRemove addObject:name];
        }
        if([array count] == [toRemove count])
            [sectionsToRemove addObject:key];

        [array removeObjectsInArray:toRemove];
        [toRemove release];
    }
    [self.keys removeObjectsInArray:sectionsToRemove];
    [sectionsToRemove release];
    [table reloadData];
}



我从这个[names valueForKey:key]的结果分配数组。
数组类型为MutableArray我缺少什么?

I am assigning array from the result of this [names valueForKey:key]; array is of type 'MutableArray' What am I missing?

谢谢!

推荐答案

valueForKey:返回 NSArray 。你可以将它发送到 NSMutableArray 并不重要。

valueForKey: returns an NSArray. It doesn't matter that you are sending it to an NSMutableArray.

您可以将结果转换为(NSMutableArray *),但我个人的偏好是得到一个副本:

You could either cast the result to (NSMutableArray *), but my personal preference is to get a copy:

NSMutableArray *array = [[[names valueForKey:key] mutableCopy] autorelease];

这篇关于为什么我得到:“mutating method sent to immutable object”当尝试从MutableArray中删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆