检查NSString崩溃的子串 [英] Check for substring of NSString crashing

查看:95
本文介绍了检查NSString崩溃的子串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试过以两种方式检查NSString中子串的出现,两者都崩溃了。这是我从NSManagedObject的一个属性获取的NSString对象。

I've tried checking for an occurrence of a substring in an NSString in two ways, both have crashed. This is an NSString object I get from one of my NSManagedObject's properties.


  1. 使用NSRange

  1. Using NSRange

NSString * searchString = @drive;

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

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

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

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

使用NSScanner

Using NSScanner

NSScanner * scanner = [NSScanner scannerWithString:text];

NSScanner *scanner = [NSScanner scannerWithString:text];

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

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

当text = @drive时,这两个工作都会起作用但是当文本导致EXC_BAD_ACCESS崩溃时是我开车,或开车去。如果文本是idrive或driveto,则没有任何反应。

Both of these work when text = @"drive" but cause EXC_BAD_ACCESS crashes when the text is "i drive", or "drive to". Nothing happens if the text is "idrive" or "driveto".

甚至更奇怪,有时示例抛出NSInvalidArgumentExceptions,说我试图传递NSCFSet或DateComponents对象到rangeOfString:,我在我的应用程序中都没有使用它。

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.

任何想法?

推荐答案

如果你有时得到 EXC_BAD_ACCESS 有时会收到消息对象类型 - 你不期望不响应方法很可能你没有足够长时间地保留对象,并且在你到达你使用它的地方之前它已被释放。

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.

如果你没有重用内存到那里,事情似乎会起作用。如果空间已被重用于另一个对象并且完全对齐,即同一指针,则会得到类似x不响应选择器的内容。如果它以指针未指向有效对象的方式被覆盖,您将获得 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 i.e. same pointer, you'll get something like "x does not respond to selector". If it's overwritten in such a way that the pointer does not point to a valid object, you'll get EXC_BAD_ACCESS

这篇关于检查NSString崩溃的子串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆