xcode 如何通过键删除 NSMutableArray 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7212320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to remove an NSMutableArray object by key?
提问by Mahmoud
i have structured an NSMutableArray and here is an example
我已经构建了一个 NSMutableArray,这是一个例子
( { Account = A; Type = Electricity; }, { Account = B; Type = Water; }, { Account = C; Type = Mobile; } )
( { Account = A; Type = Electricity; }, { Account = B; Type = Water; }, { Account = C; Type = Mobile; } )
when i try to delete Account B using
当我尝试使用删除帐户 B 时
[data removeObject:@"B"];
[数据删除对象:@"B"];
Nothing Happens
没发生什么事
[[NSUserDefaults standardUserDefaults] synchronize];
NSArray *archivedArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[self dataFilePath]];
if (archivedArray == nil) {
data = [[NSMutableArray alloc] init];
} else {
data = [[NSMutableArray alloc] initWithArray:archivedArray];
}
回答by jtbandes
If you're actually using an array and not a dictionary, you need to search for the item before you can remove it:
如果您实际上使用的是数组而不是字典,则需要先搜索该项目,然后才能删除它:
NSUInteger index = [data indexOfObjectPassingTest:^BOOL (id obj, NSUInteger idx, BOOL *stop) {
return [[(NSDictionary *)obj objectForKey:@"Account"] isEqualToString:@"B"];
}];
if (index != NSNotFound) {
[data removeObjectAtIndex:index];
}
回答by Dair
Alternative: try a NSMutableDictionary
:
替代方案:尝试一个NSMutableDictionary
:
NSArray *accounts = [NSArray arrayWithObjects:@"A", @"B", @"C", nil];
NSArray *types = [NSArray arrayWithObjects:@"Electricity", @"Water", @"Mobile", nil];
NSMutableDictionary* data = [NSMutableDictionary dictionaryWithObjects:types forKeys:accounts];
[data removeObjectForKey:@"B"];
回答by Antwan van Houdt
An NSArray
is like a list of pointers, each pointer points to an object.
AnNSArray
就像一个指针列表,每个指针都指向一个对象。
If you call:
如果你打电话:
[someArray removeObject:@"B"];
You create a new NSString
object that contains the string "B". The address to this object is different from the NSString
object in the array. Therefore NSArray
cannot find it.
您创建一个NSString
包含字符串“B”的新对象。此对象的地址NSString
与数组中的对象不同。因此NSArray
找不到它。
You will need to loop through the array and determine where the object is located, then you simply remove it by using removeObjectAtIndex:
您将需要遍历数组并确定对象所在的位置,然后您只需使用 removeObjectAtIndex: