how to check if NSString = a specific string value?

走远了吗. 提交于 2019-11-27 19:13:04
Vanya
if ([mystring isEqualToString:@"Johns"]){
    //do some stuff in here
}

Here is another method you might want to use in some circumstances:

NSArray * validNames = @[ @"foo" , @"bar" , @"bob" ];

if ([validNames indexOfObject:myString].location != NSNotFound) 
{
    // The myString is one of the names in the valid names array
}

Or if you have a large amount of names in the array you could use a NSSet, since finding an object is faster than in an array ((O(Log N) vs O(N))

NSSet * validNamesSet = [NSSet setWithArray:validNames];

if ([validNamesSet containsObject:myString]) 
{
    // This is faster than indexOfObject for large sets
}

These methods work because NSSet and NSArray use isEqual: which will call isEqualToString: for NSString instances.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!