我已经意识到matchInString方法有一个内存泄漏。 我做错了什么,或者这真的是泄漏的核心方法? 如果泄漏,那么使用正则表达式的替代方案是什么? (我知道我可以编写所有自己的代码,但我正在寻找可重用的东西) 我的代码只是试图删除String的一些特定参数。
print ("Memory Leak Test ");
for var i in 1...1000000 {
print("Memory Leak Test " + String(i));
let sMyString:String="opacity:0.71889403;fill:#0000ff;fill-opacity:1;stroke:#0000ff;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;display:inline\"/></svg>"
var stringsuche:String = "fill:(.*?);";
let regex = try! NSRegularExpression(pattern: stringsuche, options: [])
let results = regex.matchesInString(sMyString, options: [], range: NSMakeRange(0, sMyString.length))
}
print("End Memory Leak Test ");
UPDAT 我只是为此编写了自己的代码,但这种经历让我感觉很糟糕。我想有很多核心方法正在泄漏。刚发现“stringByTrimmingCharactersInSet”&amp; “stringByReplacingOccurrencesOfString”也泄密了!
func getstylevalue(styleprop:String, text:String) -> String{
var returnvalue="";
let stringsuche:String=styleprop;
let indexstart=text.indexOf(stringsuche);
if indexstart == -1 {
return returnvalue;
}else{
let indexend=text.indexOf(";", startIndex: indexstart) ;
if indexend == -1 {
return returnvalue;
}else{
returnvalue=text.substring(indexstart + stringsuche.length, endIndex: indexend);
return returnvalue;
}
}
}
内存泄漏并修剪:
print("Start Memory Leak Test ");
for i in 1...1000000 {
let theword:String=" bla ";
let temp:String = theword.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
print("End Memory Leak Test ");
答案 0 :(得分:0)
尝试autoreleasepool {}
解决内存周期(泄漏)问题。
extension String {
func regexSearch(pattern pattern: String) -> [String] {
let nsString: NSString = NSString(UTF8String: self)!
var stringGroupMatches = [String]()
do {
let regex = try NSRegularExpression(pattern: pattern, options: [])
let nsRangeAll = NSRange(location: 0, length: nsString.length)
autoreleasepool {
let matches = regex.matchesInString( nsString as String, options: [], range: nsRangeAll)
for match: NSTextCheckingResult in matches {
let rangeCount = match.numberOfRanges
// remember: $0th match is whole pattern
for group in 0 ..< rangeCount {
let r: NSRange = match.rangeAtIndex(group)
stringGroupMatches.append(nsString.substringWithRange(r))
}
}
}
return stringGroupMatches
}
catch {
return []
}
}
}