2016-11-26 3 views
0

Все остальные BAD_ACCESS я был до того, как правило, быстро опечатка исправить, но это один очень запутаннымPhantom EXC_BAD_ACCESS

Этот код должен скачать Микросхемы Google файл календаря, а затем передать его в функцию синтаксического анализатора, что возвращает массив объектов событий (не включены здесь)

проблема при тестировании на физическом устройстве IOS, каждый третий-четвёртый пробег loadEventIntoCalendar() происходит EXC_BAD_ACCESS выбрасывается, когда эта линия называется

tempHold = calendarString.substring(with: tempRange)

в цикле while функции event().

Я пробовал решить эту проблему с помощью множества различных методов. Объекты зомби прямо не печатают ничего в журнале. Я пробовал анализировать прогоны с Инструменты, но я не нашел там ничего полезного. Я попытался сделать отдельную копию файла String, переданного в аргументах, но ничего не изменил.

Я уверен, что проблема имеет какое-то отношение к calendarString или, по крайней мере, значение, на которое указывает. Я попытался проанализировать блоки памяти через Xcode, но я не смог найти никаких переменных, которые указывали бы на место памяти, которое вызывает ошибку.

Я уверен, что RAM не будет перегружена, как и всем приложение занимает около 70 мегабайтов макса (Checked с инструментами)

событий() должно быть синглтон статической функцией.

Вот две функции

func loadEventsIntoCalendar() { 
    // The link from which the calendar is downloaded 
    let url = URL (string: "https://calendar.google.com/calendar/ical/wlmacci%40gmail.com/public/basic.ics")! 


    // The process of downloading and parsing the calendar 
    let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in 
     // The following is simply a declaration and will not execute without the line 'task.resume()' 
     if let URLContent = data { // If Data has been loaded 
      // If you got to this point then you've downloaded the calendar so... 
      // Calendar File parsing starts here!!! 
      // The string that holds the contents of the calendar's events 
      var webContent:String = String(data: URLContent, encoding:String.Encoding.utf8)! 
      self.events(forCalendarFile: &webContent, inCalendar: Calendar(identifier: Calendar.Identifier.gregorian)) 
     } 
    }) 
    task.resume() 
} 

// Calendar Parser for this VC 
func events(forCalendarFile webContent:inout String, inCalendar calendar:Calendar) { 
    // The reason for this complication is, i thought copying the object might solve the issue, it did not :(
    let NSWebContent = NSString(string: webContent) 
    let calendarString = NSWebContent.copy() as! NSString 

    // An array of flags used for locating the event fields 
    // [h][0] - The flag that marks the begining of a field, [h][1] - The flag that marks the end of a field 
    let searchTitles:[[String]] = [["SUMMARY:", "TRANSP:"], ["DESCRIPTION:", "LAST-MODIFIED:"], ["DTSTART", "DTEND"], ["DTEND", "DTSTAMP"], ["LOCATION:", "SEQUENCE:"]] 

    // The range of "webContent's" content that is to be scanned 
    // Must be decreased after each event is scanned 
    var range:NSRange = NSMakeRange(0, calendarString.length - 1) 
    // Inside function that will be used to determine the 'difference' range between the begining and end flag ranges. 
    let findDifference:(NSRange, NSRange) -> NSRange = {(first:NSRange, second:NSRange) -> NSRange in 
     let location = first.location + first.length, length = second.location - location // Determine the start position and length of our new range 
     return NSMakeRange(location, length)            // Create and return the new range 
    } 
    // Inside function that will be used to move the searching range to the next event 
    // Returns an NSNotFound range (NSNotFound, 0) if there are no more events 
    let updateRange:(NSRange) -> NSRange = {(oldRange:NSRange) -> NSRange in 
     let beginingDeclaration = calendarString.range(of: "BEGIN:VEVENT", options: NSString.CompareOptions.literal, range: oldRange) 
     // If the "BEGIN:VEVENT" was not found in webContent (no more events) 
     if NSEqualRanges(beginingDeclaration, NSMakeRange(NSNotFound, 0)) { 
      return beginingDeclaration // Return an 'NSNotFound' range (Named it myself;) 
     } 
     // Calculate the index of the last character of 'beginingDeclaration' flag 
     let endOfBeginingDeclaration = beginingDeclaration.location + beginingDeclaration.length 
     // Calculate the length of the new range 
     let length = oldRange.length - endOfBeginingDeclaration + oldRange.location 
     // Calculate the starting location of the new range 
     let location = endOfBeginingDeclaration 
     // Create and return the new range 
     return NSMakeRange(location, length) 
    } 

    // A holder for the begining and end flags for each event field 
    var fieldBoundaries:[NSRange] 
    // The actual parsing of each event 
    repeat { 
     range = updateRange(range) // Move our searching range to the next event 
     if NSEqualRanges(range, NSMakeRange(NSNotFound, 0)) { // If there are no more events in the searching range 
      break;            // Then no more shall be added (break from the loop) 
     } 

     var tempHold:String! 
     // Record each field into our event database 
     for h in 0...searchTitles.count-1 { 
      fieldBoundaries = [NSRange]() // Clear the fieldBoundaries for the new search 
      fieldBoundaries.append(calendarString.range(of: searchTitles[h][0], options: NSString.CompareOptions.literal, range: range)) // Find the begining flag 
      fieldBoundaries.append(calendarString.range(of: searchTitles[h][1], options: NSString.CompareOptions.literal, range: range)) // Find the ending flag 
      let tempRange = findDifference(fieldBoundaries[0], fieldBoundaries[1]) 
      print ("Isolating event content") 
      tempHold = calendarString.substring(with: tempRange)       // Create a new string from whatever is in between the two flags. This will be the current field of the event 
      print ("Event content isolated") 
      tempHold = tempHold.trimmingCharacters(in: CharacterSet.newlines)           // Remove all /r /n and other 'new line' characters from the event field 
      tempHold = tempHold.replacingOccurrences(of: "\u{005C}", with: "", options: .literal, range: nil)   // Replace all backslashes from the event field 
     } 
    } while (true) 
} 

Это должно быть завершено в относительно короткие сроки, поэтому быстрые ответы будут весьма благодарны.

Заранее благодарен!

+0

Вы пытались поставить точку останова на строку 'tempHold = calendarString.substring (с помощью: tempRange)' или записывать 'tempRange' и' calendarString' непосредственно перед этим? –

+0

Проблема заключалась в том, что некоторые компоненты внутри памяти были повреждены на полпути через прогон, поэтому точка останова не показала бы мне многого, за исключением полностью живой переменной в одной точке и поврежденной в следующем. Не показывает мне источник ошибки – sketch204

ответ

0

На самом деле, что я в конечном итоге делает полностью переписывать алгоритм. Он работает немного по-другому и на самом деле на 20 строк короче и намного быстрее.

Спасибо за внимание, хотя! Цените помощь :)

0

Насколько я знаю, методы поиска строк не гарантируют, что длина результирующего диапазона будет 0. Что произойдет, если вы замените две проверки диапазона?

if range.location == NSNotFound { ... } 

вместо

if NSEqualRanges(range, NSMakeRange(NSNotFound, 0)) { ... } 
+0

Насколько я знаю, NSNotFound - это число, а не диапазон, поэтому я не думаю, что эта строка будет работать, но в любом случае спасибо. – sketch204