【发布时间】:2014-05-07 18:12:08
【问题描述】:
我在删除名称/ID 在我的 NSMutableArray 中的所有节点时遇到了一些麻烦。 我已将每个对象的值设置为唯一名称。所以我只能删除 NSMutableArray 中的那些。
对象在循环中创建,每个对象的名称都是唯一的。
像这样:
myObject.name = @"8dAN3kgh6E";
下一个循环
myObject.name = @"WsFkdGrmHm";
下一个循环
myObject.name = @"ov5BjzHGiw";
然后将这些值相加并存储在一个数组中。
NSMutableArray *currentShapeArray
(
8dAN3kgh6E,
WsFkdGrmHm,
ov5BjzHGiw
)
然后我循环遍历 currentShapeArray,我就是这样做的:
for (NSString *myObjectNames in currentShapeArray) {
NSLog(@"%@", myObjectNames); //works and gives each value correctly
}
但是对于我的生活,我似乎无法弄清楚如何在这一点上删除包含该特定 node.name 的对象。
类似于 [myObject removeFromParent]; ...但我需要根据 myObject.name 属性进行选择。
我确信这很简单,希望有人可以帮助我朝正确的方向发展。谢谢!
更新:1.
我尝试了 sangony 的建议,由于某种原因,当我使用它时它给了我以下错误。
2014-05-07 23:11:56.163 dotmatcher[1149:60b] NODE NAME: FY7opRB1Wk
2014-05-07 23:11:56.164 dotmatcher[1149:60b] ButtonTmp 1
2014-05-07 23:11:56.164 dotmatcher[1149:60b] Previous 1
2014-05-07 23:11:56.164 dotmatcher[1149:60b] -[__NSCFString name]: unrecognized selector sent to instance 0xee1fe50
2014-05-07 23:11:56.167 dotmatcher[1149:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString name]: unrecognized selector sent to instance 0xee1fe50'
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
for (UITouch *touch in touches) {
UITouch* touch = [touches anyObject];
CGPoint loc = [touch locationInNode:self];
NSArray *nodes = [self nodesAtPoint:loc];
for (SKNode *node in nodes) {
NSString *tmp = node.name;
if (tmp.length !=0) {
NSLog(@"ended");
NSString *buttonTmp = [node.userData objectForKey:@"buttonType"];
if ([buttonTmp isEqualToString:@"1"] && [previousButton isEqualToString:@"1"]) {
endButton = @"1";
NSLog(@"NODE NAME: %@",node.name);
NSLog(@"ButtonTmp %@", buttonTmp);
NSLog(@"Previous %@", previousButton);
NSMutableArray *discardedItems = [NSMutableArray array];
for(SKNode *object in currentShapeArray)
{
if([object.name isEqualToString:node.name])
{
[object removeFromParent]; // not sure if you need this or not
[discardedItems addObject:object];
}
}
[currentShapeArray removeObjectsInArray:discardedItems];
NSLog(@"ButtonID: %@",[node.userData objectForKey:@"buttonID"]);
NSLog(@"ButtonType: %@",[node.userData objectForKey:@"buttonType"]);
NSLog(@"ButtonColumn: %@",[node.userData objectForKey:@"buttonColumn"]);
NSLog(@"ButtonRow: %@",[node.userData objectForKey:@"buttonRow"]);
NSLog(@"AFTER REMOVE%@",currentShapeArray);
}
}
}
}
}
UPDATE 2 这是让它工作的最终代码。谢谢桑尼!
NSMutableArray *discardedItems = [NSMutableArray array];
for(SKNode *object in currentShapeArray)
{
[object removeFromParent];
[discardedItems addObject:object];
}
[currentShapeArray removeObjectsInArray:discardedItems];
【问题讨论】:
-
将节点存储在数组中会简单得多,或者如果您可以将它们全部添加到同一个节点而不是其他节点,这样您就可以使用该节点的子节点,这样会更好数组作为您的存储,并能够使用 enumerateChildNodes...
-
@LearnCocos2D 这样做而不是 sangony 提到的方式有什么好处?
-
因为您可以免费获得“按名称获取”和带有名称的枚举,并且不需要额外的存储空间,也不需要额外的代码来向自定义数组添加/删除节点以保持同步,从而减少潜在的编码错误。
-
@LearnCocos2D 我明白了.... 看起来我有一小部分要重新编码 :) 感谢您的提示。
标签: ios objective-c sprite-kit