Xcode 检查数组是否包含特定字符串
我正在数组中保存不同的代码,现在想检查数组中是否有一个代码 我四处找了找,但什么也没找到 在这里您可以看到我的阵列的外观:Xcode 检查数组是否包含特定字符串,xcode,arrays,nsarray,contains,Xcode,Arrays,Nsarray,Contains,我正在数组中保存不同的代码,现在想检查数组中是否有一个代码 我四处找了找,但什么也没找到 在这里您可以看到我的阵列的外观: 2013-04-28 12:43:23.877 myApp[9422:907] PushArray: ( { code = 123; titel = "Test 01"; }, { code = 456; titel = "Test 02"; }, { code = 789; titel = "Test
2013-04-28 12:43:23.877 myApp[9422:907] PushArray: (
{
code = 123;
titel = "Test 01";
},
{
code = 456;
titel = "Test 02";
},
{
code = 789;
titel = "Test 03";
}
)
NSString *code = [NSString stringWithFormat:@"123"];;
if ([PushArray containsObject:code]) {
NSLog(@"Code true!");
}else {
NSLog(@"Code false!");
}
我尝试检查:
2013-04-28 12:43:23.877 myApp[9422:907] PushArray: (
{
code = 123;
titel = "Test 01";
},
{
code = 456;
titel = "Test 02";
},
{
code = 789;
titel = "Test 03";
}
)
NSString *code = [NSString stringWithFormat:@"123"];;
if ([PushArray containsObject:code]) {
NSLog(@"Code true!");
}else {
NSLog(@"Code false!");
}
但是每次我得到“代码错误!”返回…数组中的对象实际上是NSDictionary对象。因此,为了比较数字,让我们在数组上枚举,并对来自该dictionary对象的值进行比较:
NSNumber * code = [NSNumber numberWithInteger: 123];
for(NSDictionary * anEntry in pushArray)
{
NSNumber * numberFromEntry = [anEntry objectForKey: @"code"];
if([code isEqualToNumber: numberFromEntry])
NSLog( @"code true!");
}
另外,请注意,我将数组的名称从“PushArray
”更改为“PushArray
”。标准Objective-C约定是变量和对象使用小写字母,类命名使用大写字母
(我的答案的原始版本——我很快捕捉并编辑了答案——是比较字符串;但我猜dictionary对象中的那些代码值实际上是数字而不是字符串)哦,该死的,我忘了数组中有一个dict://非常感谢,u代码可以工作!有没有一种方法可以从“for”获取返回值为“code true”或“code false”的NSString?而不是“
NSLog”(@“code true!”);
”,执行“返回@“code true”;
”(假设函数的返回类型是NSString)完美,并且是否有可能删除字典中包含代码的所有条目,如if([code IsequalNumber:numberFromEntry])删除条目代码>非常感谢您的帮助!:)只有当我们使用的是可变字典或可变数组时。