试图在NSMutableArray中获取对象的索引。它返回一些垃圾值,不知道为什么它不返回特定项的索引。下面是我试过的代码
NSString *type = [dictRow valueForKey:@"type"];
if([arrSeatSel indexOfObject:type])
{
NSUInteger ind = [arrSeatSel indexOfObject:type];
[arrTotRows addObject:[arrSeatSel objectAtIndex:ind]];
}
类型包含值"Gold"。而arrSeatSel包含
(
"Gold:0",
"Silver:0",
"Bronze:1"
如何检查。请指导。
您得到的值是NSNotFound
。你得到NSNotFound
是因为@"Gold"
不等于@"Gold:0"
。
你应该试试下面的
NSUInteger index = [arrSeatSel indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop){
return [obj hasPrefix:type];
}];
if (index != NSNotFound) {
[arrTotRows addObject:[arrSeatSel objectAtIndex:index]];
}
-indexOfObjectPassingTest:
是一个正在运行的循环。注意:/* TEST */
是一些代码,当找到正确的索引时返回true。
NSUInteger index = NSNotFound;
for (NSUInteger i = 0; i < [array count]; ++i) {
if (/* TEST */) {
index = i;
break;
}
}
在我的第一个示例中,/* TEST */
是[obj hasPrefix:type]
。最后一个for循环看起来像。
NSUInteger index = NSNotFound;
for (NSUInteger i = 0; i < [arrSeatSel count]; ++i) {
if ([arrSeatSel[i] hasPrefix:type]) {
index = i;
break;
}
}
if (index != NSNotFound) {
[arrTotRows addObject:[arrSeatSel objectAtIndex:index]];
}
我更喜欢-indexOfObjectPassingTest:
。
[obj hasPrefix:type]
部分只是比较字符串的另一种方式。阅读-hasPrefix:
文档了解更多细节。
希望这能回答你所有的问题。
有时正确存储数据可以解决很多混乱。如果我猜对了
"Gold:0"
表示类型为Gold的圆圈,其计数为0。
您可以尝试将其重新格式化为项数组。
如
[
{
"Type": "Gold",
"Count": 0
},
{
"Type": "Silver",
"Count": 0
},
{
"Type": "Bronze",
"Count": 1
}
]
然后使用谓词查找索引
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Type == %@",@"Gold"];
NSUInteger index = [types indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
[predicate evaluateWithObject:obj];
}];
你可以试试。
[arrSeatSel enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
// object - will be your "type"
// idx - will be the index of your type.
}];
如果我没看错,你是说arrSeatSel
包含三个NSString
s, @"Gold:0"
, @"Silver:0"
和@"Bronze:1"
,对吗?
然后NSString* type
就是@"Gold"
第一件事是Gold
和Gold:0
是不同的字符串,这只是初学者。
当您在数组中搜索字符串时,您应该取出每个字符串,并进行字符串匹配,而不仅仅是比较。我要说的是:
NSString* str1 = @"This is a string";
NSString* str2 = @"This is a string";
if ( str1 == str 2 ) NSLog(@"Miracle does happen!")
即使两个NSString
包含相同的值,条件也永远不会为真,它们是不同的对象,因此是指向不同内存块的不同指针。
你在这里应该做的是一个字符串匹配,我在这里推荐NSString
的hasPrefix:
方法,因为它似乎适合你的需要。