Objective c 在NSMutable数组中比较NSString时出现问题
我编写了一个方法,在一个按钮数组中循环,并检查字符串是否等于数组中的任何按钮标题,但它不起作用,尽管传递给该方法的字符串等于数组中的一些字符串,我的代码如下:Objective c 在NSMutable数组中比较NSString时出现问题,objective-c,ios,xcode,Objective C,Ios,Xcode,我编写了一个方法,在一个按钮数组中循环,并检查字符串是否等于数组中的任何按钮标题,但它不起作用,尽管传递给该方法的字符串等于数组中的一些字符串,我的代码如下: -(void)checkDuplicatesInSection:(NSString*)btnLabel { for (UIButton* btn in self.test) { if([btnLabel isEqualToString:btn.titleLabel.text]) {
-(void)checkDuplicatesInSection:(NSString*)btnLabel
{
for (UIButton* btn in self.test) {
if([btnLabel isEqualToString:btn.titleLabel.text])
{
NSLog(@"Inside check Dublicates--->Title Existed");
} else {
NSLog(@"Inside check Dublicates--->Title Not Existed");
}
}
}
// self.test---> it's an array contains group of buttons
// btnLabel----> it's a string passed to that method
我不明白的是,为什么当我运行程序时,我同时得到内部检查副本-->标题存在
和“内部检查副本-->标题不存在
代码:
if([btnLabel isEqualToString:btn.titleLabel.text])
{
NSLog(@"Inside check Dublicates--->Title Existed");
} else {
NSLog(@"Inside check Dublicates--->Title Not Existed");
}
将多次执行,因为它位于for
循环中。这就是为什么在运行代码时会打印两个日志的原因
要测试self.test
是否包含字符串btn.titleLabel.text
,您应该将代码修改为:
-(void)checkDuplicatesInSection:(NSString*)btnLabel
{
BOOL found = NO;
for (UIButton* btn in self.test) {
if([btnLabel isEqualToString:btn.titleLabel.text]) {
found = YES;
break;
}
}
if (found) {
NSLog(@"Inside check Dublicates--->Title Existed");
} else {
NSLog(@"Inside check Dublicates--->Title Not Existed");
}
}
或者您可以简单地使用方法*:
*即使
btn.titleLabel.text
是一个NSString
这个问题让人困惑。我清理了格式,但您能重申或详细说明您的问题吗?如果([btnLabel IsequalString:btn.titleLabel.text]))虽然我打印了按钮标题并且数组工作正常,但当我删除btn.titleLabel.text并放入一个常量字符串时,该语句不正常!!您可以注销您的self.test
array吗?其中一个指针可能不是UIButton
。
-(void)checkDuplicatesInSection:(NSString*)btnLabel
{
BOOL found = [self.test containsObject:btn.titleLabel.text];
if (found) {
NSLog(@"Inside check Dublicates--->Title Existed");
} else {
NSLog(@"Inside check Dublicates--->Title Not Existed");
}
}