2015-06-25 10 views
3

Чтобы обобщить мою проблему, я пытаюсь проверить источник данных коллекционного представления. I Инициализируйте контроллер представления и вызовите viewDidLoad() для инициализации компонентов, которые инициализируют настраиваемый класс для использования в качестве источника данных. Это класс, который я тестирую.UICollectionView Unit Test Плохой доступ к dequeueReusableCellWithReuseIdentifier

Программа начинается в модульном тесте здесь:

class BubbleViewManagerTest: XCTestCase { 

var viewController : DashboardViewController = DashboardViewController() 
//var bubbleViewManager : BubbleViewManager = BubbleViewManager() 

override func setUp() { 
    super.setUp() 

    let storyboard = UIStoryboard(name: "Main", bundle: NSBundle(forClass: self.dynamicType)) 
    viewController = storyboard.instantiateViewControllerWithIdentifier("DashboardViewControllerId") as! DashboardViewController 
    bubbleViewManager = viewController.bubbleViewManager 
    viewController.loadView() 
    viewController.viewDidLoad() 
} 

func testCellForItemAtIndexPath() { 
    DataManager.singleton.dayActivities = [] 

    DataManager.singleton.addGoal(Period(name: "asdf", hour: 1, minute: 1, color: UIColor.blackColor(), priority: PeriodPriority.Low)) 

    var cell = bubbleViewManager.collectionView(viewController.bubbleView, cellForItemAtIndexPath: NSIndexPath(forRow: 0, inSection: 0)) as! BubbleCollectionViewCell 

    XCTAssertEqual(cell.bounds.width, 45) 
    XCTAssertEqual(cell.bounds.height, 45) 
    XCTAssertNotNil(cell.bubbleView.period) 

    DataManager.singleton.addGoal(Period(name: "asdf", hour: 1, minute: 1, color: UIColor.blackColor(), priority: PeriodPriority.Medium)) 
    DataManager.singleton.addGoal(Period(name: "asdf", hour: 1, minute: 1, color: UIColor.blackColor(), priority: PeriodPriority.High)) 

    var index = NSIndexPath(forRow: 1, inSection: 0) 

    cell = bubbleViewManager.collectionView(viewController.bubbleView, cellForItemAtIndexPath: index) as! BubbleCollectionViewCell 

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 

    let period: Period = DataManager.singleton.dayActivities[indexPath.row] 
    var cell: BubbleCollectionViewCell = BubbleCollectionViewCell() 

    switch period.priority { 
     case .High: 
      cell = collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifierHighPriority, forIndexPath: indexPath) as! BubbleCollectionViewCell 
      break; 
     case .Medium: 
      cell = collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifierMediumPriority, forIndexPath: indexPath) as! BubbleCollectionViewCell 
      break; 
     case .Low: 
      cell = collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifierLowPriority, forIndexPath: indexPath) as! BubbleCollectionViewCell 
    } 

    // Give the bubble view the period for it to work on. 
    cell.bubbleView.period = period 


    // The bubble view needs to monitor a timer to redraw the bubble. Observer is assigned here. 
    if let timer = cell.bubbleView.period?.globalTimer { 
     timer.observer = cell.bubbleView 
    } 

    return cell 
} 

Программа перерывов на линии cell = collectionView.dequeueReusableCellWithReuseIdentifier(self.reuseIdentifierMediumPriority, forIndexPath: indexPath) as! BubbleCollectionViewCell

я понимаю EXC_BAD_ACCESS происходит, когда объект доступен после того, как он autoreleased или когда он не инициализирован в первую очередь. В моем случае я получаю ошибку и убедился, что все объекты инициализированы, а их ссылки сильны (не слабы). Я включил NSZombies и не повезло с этим.

Что меня смущает, так это то, что func collectionView(collectionView:cellForItemAtIndexPath:) -> UICollectionViewCell выполнил один раз уже до разрыва потока.

Возможно, это связано с тем, что я запускаю тестовую цель? Этот код работает так, как ожидалось, когда я запускаю приложение на iOS Simulator.

Любая помощь была бы принята с благодарностью.

ответ

2

Это было решено путем вызова reloadData() после добавления новых данных для тестирования. При попытке имитировать контроллер вида для проверки источника данных. viewController.collectionView.reloadData(). Я никогда не рассматривал это, потому что это сделано в вызове viewDidLoad(), и это было сделано до добавления данных.

 Смежные вопросы

  • Нет связанных вопросов^_^