gpt4 book ai didi

objective-c - 为什么我收到 : "mutating method sent to immutable object" when trying remove from MutableArray?

转载 作者:行者123 更新时间:2023-12-03 16:23:35 25 4
gpt4 key购买 nike

我不明白为什么我在这段代码中收到“发送到不可变对象(immutable对象)的变异方法”。该数组必须以某种方式是不可变的,但我不知道为什么。

界面:

    @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

请注意,names 是一个 MutableDictionary。

下面一行抛出异常

[array removeObjectsInArray:toRemove];

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

-(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”我缺少什么?

谢谢!

最佳答案

valueForKey: 返回一个 NSArray。将其发送到 NSMutableArray 并不重要。

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

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

关于objective-c - 为什么我收到 : "mutating method sent to immutable object" when trying remove from MutableArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5707360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com