简体   繁体   English

检查NSString崩溃的子串

[英]Check for substring of NSString crashing

I've tried checking for an occurrence of a substring in an NSString in two ways, both have crashed. 我试过用两种方式检查NSString中子串的出现,两者都崩溃了。 This is an NSString object I get from one of my NSManagedObject's properties. 这是我从NSManagedObject的一个属性中获取的NSString对象。

  1. Using NSRange 使用NSRange

    NSString *searchString = @"drive";

    NSRange range = [text rangeOfString:searchString options:(NSCaseInsensitiveSearch)];

    if (range.location != NSNotFound) { NSLog(@"Found"); }

  2. Using NSScanner 使用NSScanner

    NSScanner *scanner = [NSScanner scannerWithString:text];

    NSLog(@"%d",[scanner scanString:searchString intoString:nil]);

Both of these work when text = @"drive" but cause EXC_BAD_ACCESS crashes when the text is "i drive", or "drive to". 当text = @“drive”时,这两个都有效,但当文本为“i drive”或“drive to”时,导致EXC_BAD_ACCESS崩溃。 Nothing happens if the text is "idrive" or "driveto". 如果文本是“idrive”或“driveto”,则没有任何反应。

Even stranger, sometimes the examples throw NSInvalidArgumentExceptions, saying that I tried to pass an NSCFSet or a DateComponents object to rangeOfString:, neither of which I use in my app. 甚至更奇怪,有时示例抛出NSInvalidArgumentExceptions,说我试图将NSCFSet或DateComponents对象传递给rangeOfString:,我在我的应用程序中都没有使用它们。

Any ideas? 有任何想法吗?

The following worked perfectly for me including the spaces. 以下对我来说非常有效,包括空间。

NSString *string = @"hello one two three";
if ([string rangeOfString:@"one two"].location == NSNotFound) {
    NSLog(@"string does not contain substring");
} else {
    NSLog(@"string contains substring!");
}

And if you want it to be case insensitive, just convert both the string and the search string to lowercase. 如果您希望它不区分大小写,只需将字符串和搜索字符串转换为小写。 You should be knowing how to do that I guess. 你应该知道如何做到这一点。

If you sometimes get EXC_BAD_ACCESS and sometimes get the message " object-of-type-you-weren't expecting does not respond to method " the chances are you are not retaining the object for long enough and it is getting deallocated before you get to where you use it. 如果你有时得到EXC_BAD_ACCESS并且有时会得到消息“ 类型对象 - 你期望没有对方法做出响应”,那么你很可能没有长时间保留对象并且在你到达之前它被释放了在哪里使用它。

If the memory hasn't been reused when you get there, things will appear to work. 如果到达目的地后内存没有被重用,事情就会起作用。 If the space has been reused for another object and aligns perfectly ie same pointer, you'll get something like "x does not respond to selector". 如果空间已被重用于另一个对象并且完全对齐,即相同的指针,则会得到类似“x不响应选择器”的内容。 If it's overwritten in such a way that the pointer does not point to a valid object, you'll get EXC_BAD_ACCESS 如果以指针未指向有效对象的方式覆盖它,您将获得EXC_BAD_ACCESS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM