Swift WatchKit Tables Found nil while unwrapping optional - ios

I've seen a bunch of threads reporting this error, however, after trying all solutions, I still have the same problem. Running with the debugger I can see that the .setNumberOfRows method works, as it assigns the appropriate number of rows to my table.
import WatchKit
import Foundation
class CountInterfaceController: WKInterfaceController {
//MARK: Properties
#IBOutlet var dataTable: WKInterfaceTable!
var counters = [Counter]()
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
if let savedCounters = loadCounters(){
counters+=savedCounters
}else{
loadSampleCounters()
}
dataTable.setNumberOfRows(counters.count, withRowType: "CountRowController")
for(index, counter) in counters.enumerated(){
let row = dataTable.rowController(at: index) as! CountRowController
row.countNameLabel.setText(counter.name)
row.countCounterLabel.setText("\(counter.count)")
}
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
private func loadSampleCounters(){
guard let counter1 = Counter(name:"Pots of coffee", count: 20) else {
fatalError("Unable to instantiate counter 1")
}
guard let counter2 = Counter(name:"Tea kettles", count: 5) else {
fatalError("Unable to instantiate counter 2")
}
counters += [counter1, counter2]
}
I have created a Table Row Class and added it in the Identity field of the Table Row Controller as you can see in the picture below. The class contains the outlets for the two labels in the table row.
Table Row Controller with class
I have tried populating my table with random data from a simple array of strings but that doesn't work either(same error). I honestly don't see what I'm missing here... The only thing that I can think of is that something's changed in Swift 4 as most of the answers and info that I've found were related to Swift 3.
error

Related

Networking in Swift Using WikipediaKit / Delegate Design Pattern

I'm trying to request basic info from Wikipedia - user selects tableView row and is taken to a new view that displays info associated with the row (album descriptions). Flow is:
tableView Cell passes user choice to network struct, performs segue to new view
network struct uses choice to query Wikipedia API
received info is passed via delegate method to new view
info is displayed in new view to user
Two issues I'm having:
Networking seems to not be carried out until after the new view is triggered and updated. Initially I didn't use delegate, and just had networking method return its result. But either way, I need networking to get its result back before we get to and update the new view. I've added Dispatch.main.async to the new view for the UI. I thought I may need a completion handler, but I don't fully understand this
Delegate protocol was introduced to fix problem 1, but it still doesn't work. For some reason nothing of the delegate method in the new view is triggering.
Here's the initial tableView trigger:
extension TopTenViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
albumManager.getAlbumInfo(albumTitle: topTenList[indexPath.row][1])
performSegue(withIdentifier: "topTenAlbumInfoSeg", sender: self)
}
Here is the delegate and all the networking:
protocol AlbumManagerDelegate {
func didUpdateAlbumInfo(albumInfo: String)
}
struct AlbumManager {
var newResult: String = ""
var delegate: AlbumManagerDelegate?
func getAlbumInfo(albumTitle: String) {
let wikipedia = Wikipedia.shared
let language = WikipediaLanguage("en")
let _ = wikipedia.requestArticle(language: language, title: albumTitle, imageWidth: 5) { result in
switch result {
case .success(let article):
print(article.displayTitle)
self.delegate?.didUpdateAlbumInfo(albumInfo: article.displayTitle)
print("delegate should be updated")
case .failure(let error):
print(error)
}
}
}
}
Here is the target view:
class AlbumInfoViewController: UIViewController, AlbumManagerDelegate {
#IBOutlet weak var albumDescriptionLabel: UILabel!
#IBOutlet weak var myWebView: WKWebView!
var albumDescription: String = ""
var albumManager = AlbumManager()
override func viewDidLoad() {
super.viewDidLoad()
albumManager.delegate = self
print(albumDescriptionLabel.text)
}
func didUpdateAlbumInfo(albumInfo: String) {
DispatchQueue.main.async {
print("This worked: \(albumInfo)")
self.albumDescriptionLabel.text = "Hi this is: \(albumInfo)"
}
}
}
Currently nothing in didUpdateAlbumInfo in the new view is being triggered. albumDescriptionLabel is not being updated. Could the issue be that the segue is performed too soon? Thanks in advance!

How do refresh my UITableView after reading data from FirebaseFirestore with a SnapShotListener?

UPDATE at the bottom.
I have followed the UIKit section of this Apple iOS Dev Tutorial, up to and including the Saving New Reminders section. The tutorials provide full code for download at the beginning of each section.
But, I want to get FirebaseFirestore involved. I have some other Firestore projects that work, but I always thought that I was doing something not quite right, so I'm always looking for better examples to learn from.
This is how I found Peter Friese's 3-part YT series, "Build a To-Do list with Swift UI and Firebase". While I'm not using SwiftUI, I figured that the Firestore code should probably work with just a few changes, as he creates a Repository whose sole function is to interface between app and Firestore. No UI involved. So, following his example, I added a ReminderRepository.
It doesn't work, but I'm so close. The UITableView looks empty but I know that the records are being loaded.
Stepping through in the debugger, I see that the first time the numberOfRowsInSection is called, the data hasn't been loaded from the Firestore, so it returns 0. But, eventually the code does load the data. I can see each Reminder as it's being mapped and at the end, all documents are loaded into the reminderRepository.reminders property.
But I can't figure out how to get the loadData() to make the table reload later.
ReminderRepository.swift
class ReminderRepository {
let remindersCollection = Firestore.firestore()
.collection("reminders").order(by: "date")
var reminders = [Reminder]()
init() {
loadData()
}
func loadData() {
print ("loadData")
remindersCollection.addSnapshotListener { (querySnapshot, error) in
if let querySnapshot = querySnapshot {
self.reminders = querySnapshot.documents.compactMap { document in
do {
let reminder = try document.data(as: Reminder.self)
print ("loadData: ", reminder?.title ?? "Unknown")
return reminder
} catch {
print (error)
}
return nil
}
}
print ("loadData: ", self.reminders.count)
}
}
}
The only difference from the Apple code is that in the ListDataSource.swift file, I added:
var remindersRepository: ReminderRepository
override init() {
remindersRepository = ReminderRepository()
}
and all reminders references in that file have been changed to
remindersRepository.reminders.
Do I need to provide a callback for the init()? How? I'm still a little iffy on the matter.
UPDATE: Not a full credit solution, but getting closer.
I added two lines to ReminderListViewController.viewDidLoad() as well as the referenced function:
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(refreshTournaments(_:)), for: .valueChanged)
#objc
private func refreshTournaments(_ sender: Any) {
tableView.reloadData()
refreshControl?.endRefreshing()
}
Now, when staring at the initial blank table, I pull down from the top and it refreshes. Now, how can I make it do that automatically?
Firstly create some ReminderRepositoryDelegate protocol, that will handle communication between you Controller part (in your case ReminderListDataSource ) and your model part (in your case ReminderRepository ). Then load data by delegating controller after reminder is set. here are some steps:
creating delegate protocol.
protocol ReminderRepositoryDelegate: AnyObject {
func reloadYourData()
}
Conform ReminderListDataSource to delegate protocol:
class ReminderListDataSource: UITableViewDataSource, ReminderRepositoryDelegate {
func reloadYourData() {
self.tableView.reloadData()
}
}
Add delegate weak variable to ReminderRepository that will weakly hold your controller.
class ReminderRepository {
let remindersCollection = Firestore.firestore()
.collection("reminders").order(by: "date")
var reminders = [Reminder]()
weak var delegate: ReminderRepositoryDelegate?
init() {
loadData()
}
}
set ReminderListDataSource as a delegate when creating ReminderRepository
override init() {
remindersRepository = ReminderRepository()
remindersRepository.delegate = self
}
load data after reminder is set
func loadData() {
print ("loadData")
remindersCollection.addSnapshotListener { (querySnapshot, error) in
if let querySnapshot = querySnapshot {
self.reminders = querySnapshot.documents.compactMap { document in
do {
let reminder = try document.data(as: Reminder.self)
print ("loadData: ", reminder?.title ?? "Unknown")
delegate?.reloadYourData()
return reminder
} catch {
print (error)
}
return nil
}
}
print ("loadData: ", self.reminders.count)
}
}
Please try changing var reminders = [Reminder]() to
var reminders : [Reminder] = []{
didSet {
self.tableview.reloadData()
}
}

How to refresh container view (reload table view) after getting data from firebase: Swift

I have been working on an app. I am a beginner so please ignore any mistakes.
The problem is that i have a view controller, which has 2 container view controllers controlled by a segmented control.
enter image description here
All three of them have separate classes: (say)
MainViewController
FirstViewController
SecondViewController
In the main view controller, i am getting some data from firebase, which i am storing in an array, and this array is to be passed to the first and second container views, which have their table views, which will load data based on this array which is passed.
Now before the data comes back in the MainViewController, the First and Second view controllers are already passed with an empty array, and no data loads up in their table views (obviously because the array is empty).
I want the container view controllers to load up after the data is received, and array is loaded. Any help ?, Thanks
P.s I am not performing any segue because these are container views, and they are automatically loaded as the main view container loads.
EDIT: Being more precise and clear with original code:
Originally I have 3 view controllers
SearchResultsScreenViewController (Main VC)
GuidesListSearchScreenViewController (First Container VC)
ServicesListSearchScreenViewController (Second Container VC)
In the Main VC i used a segmented control to see container vc's on screen, here:
import UIKit
import Firebase
class SearchResultsScreenViewController: UIViewController
{
#IBOutlet weak var GuideListView: UIView!
#IBOutlet weak var ServicesListView: UIView!
var searchQueryKeyword: String?
var guidesDataArray = [GuideDM]()
override func viewDidLoad()
{
super.viewDidLoad()
ServicesListView.isHidden = true
populateGuidesList()
}
#IBAction func SegmentChanged(_ sender: UISegmentedControl)
{
switch sender.selectedSegmentIndex
{
case 0:
GuideListView.isHidden = false
ServicesListView.isHidden = true
break
case 1:
GuideListView.isHidden = true
ServicesListView.isHidden = false
break
default:
break
}
}
func populateGuidesList()
{
let dbRef = Firestore.firestore().collection("guide")
dbRef.getDocuments
{ (snapshot, error) in
if let err = error
{
print(err.localizedDescription)
print("Error: Unable to find guides list")
}
else
{
if let snap = snapshot
{
print("List is started now")
for doc in snap.documents
{
if doc.exists
{
let data = doc.data()
let city = data["city"] as? String ?? ""
let province = data["province"] as? String ?? ""
let country = data["country"] as? String ?? ""
if city.localizedCaseInsensitiveContains(self.searchQueryKeyword!) || province.localizedCaseInsensitiveContains(self.searchQueryKeyword!) || country.localizedCaseInsensitiveContains(self.searchQueryKeyword!)
{
let guideId = doc.documentID
let guideEmail = data["email"] as? String ?? ""
let name = data["name"] as? String ?? ""
let dob = data["dob"] as? String ?? ""
let feeCurrency = data["feeCurrency"] as? String ?? ""
let status = data["status"] as? String ?? ""
let totalReviews = data["totalReviews"] as? Int ?? 0
let rating = data["rating"] as? Int ?? 0
let baseFee = data["baseFee"] as? Int ?? 0
let isGuideFeatured = data["isGuideFeatured"] as? Bool ?? false
//make a model of guide and append in array
let guide = GuideDM(id: guideId, email: guideEmail, name: name, dob: dob, city: city, province: province, country: country, feeCurrency: feeCurrency, status: status, baseFee: baseFee, rating: rating, totalReviews: totalReviews, isGuideFeatured: isGuideFeatured)
self.guidesDataArray.append(guide)
}
}
}
print("list is finalized now")
}
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "searchScreentoGuideListSegment"
{
let guidesListContainerVC = segue.destination as! GuidesListSearchScreenViewController
guidesListContainerVC.guidesDataArray = self.guidesDataArray
}
}
}
In the above class my code makes a call to function "populateGuidesList()" which makes a network call to get data, and at the same time loads up my container views. The problem is, before the network call returns data, the empty array gets passed to my "GuidesListSearchScreenViewController" i.e. (First container VC), which is a table view, and loads an empty table because the array is not filled yet.
My First container VC class:
import UIKit
import Firebase
class GuidesListSearchScreenViewController: UIViewController
{
#IBOutlet weak var guidesListTableView: UITableView!
var guidesDataArray = [GuideDM]()
override func viewDidLoad()
{
super.viewDidLoad()
guidesListTableView.delegate = self
guidesListTableView.dataSource = self
guidesListTableView.register(UINib(nibName: "GuidesListCellSearchScreenTableViewCell", bundle: nil), forCellReuseIdentifier: "guidesListCell")
}
}
extension GuidesListSearchScreenViewController: UITableViewDataSource, UITableViewDelegate
{
// below functions are to setup the table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return guidesDataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = guidesListTableView.dequeueReusableCell(withIdentifier: "guidesListCell") as! GuidesListCellSearchScreenTableViewCell
//adding properties to cell and then returning cell
return cell
}
}
GOAL: Either load the container view, after the data is received in the array, or refresh the table by again passing the array to container VC and reloading table.
Other solution: I had tried loading up all this array data inside First container VC class, and reloading table view data from there, which works perfectly fine, but to me which is a very inefficient approach, as i need this array in both container views, so making network calls for each container vc seems very inefficient. Therefore, i am trying to get the data once and pass in both container views. Kindly correct me if you feel me wrong.
P.s I have deleted other functionality and simplified the code.
And help would be highly appreciated.
The container view controllers will load when the main view controller is loaded. Therefore you will have to update the container view controllers when the main view controller receives the data.
A simple way to do this is to update the arrays in the container view controllers, and use a didSet on the arrays to force the container view controllers to reload themselves.
For example, if your FirstViewController displays the array data in a table view, you might do this:
var array: [ArrayItem] {
didSet {
tableView.reloadData()
}
}
Then in your main view controller, when the data is received, set this property:
getData() { resultArray in
firstViewController.array = resultArray
}
Please note, since you didn't provide any code, these are just examples and you will have to adjust them to fit your specific situation.
EDIT: Per comment below, you should be careful not to set the array in your FirstViewController before its view has loaded or the call to tableView.reloadData() will cause your app to crash.
I can only speculate without seeing the code, so here goes nothing... 😉
Try doing the following on viewDidLoad() of MainViewController:
Use the property related to FirstViewController (for the sake of my explanation let’s assume it’s named ‘firstVC’). What you want to do is go, firstVC.view.isHidden = true
Do the same to SecondViewController.
Why? Doing so will hide the container VC’s (ViewController) from the MainViewController’s view.
Now what you want to do is, at the place where you get data from Firebase (at the closure), add the following:
firstVC.view.isHidden = false
Do the same to SecondViewController.
This brings it back to view with the data you fetched already populating it.
Hopefully this helps you out some way.

Swift iOS -How To Reload TableView Outside Of Firebase Observer .childAdded to Filter Out Duplicate Values?

I have a tabBar controller with 2 tabs: tabA which contains ClassA and tabB which contains ClassB. I send data to Firebase Database in tabA/ClassA and I observe the Database in tabB/ClassB where I retrieve it and add it to a tableView. Inside the tableView's cell I show the number of sneakers that are currently inside the database.
I know the difference between .observeSingleEvent( .value) vs .observe( .childAdded). I need live updates because while the data is getting sent in tabA, if I switch to tabB, I want to to see the new data get added to the tableView once tabA/ClassA is finished.
In ClassB I have my observer in viewWillAppear. I put it inside a pullDataFromFirebase() function and every time the view appears the function runs. I also have Notification observer that listens for the data to be sent in tabA/ClassA so that it will update the tableView. The notification event runs pullDataFromFirebase() again
In ClassA, inside the callback of the call to Firebase I have the Notification post to run the pullDataFromFirebase() function in ClassB.
The issue I'm running into is if I'm in tabB while the new data is updating, when it completes, the cell that displays the data has a count and the count is thrown off. I debugged it and the the sneakerModels array that holds the data is sometimes duplicating and triplicating the newly added data.
For example if I am in Class B and there are 2 pairs of sneakers in the database, the pullDataFromFirebase() func will run, and the tableView cell will show "You have 2 pairs of sneakers"
What was happening was if I switched to tabA/ClassA, then added 1 pair of sneakers, while it's updating I switched to tabB/ClassB, the cell would still say "You have 2 pairs of sneakers" but then once it updated the cell would say "You have 5 pairs of sneakers" and 5 cells would appear? If I switched tabs and came back it would correctly show "You have 3 pairs of sneakers" and the correct amount of cells.
That's where the Notification came in. Once I added that if I went through the same process and started with 2 sneakers the cell would say "You have 2 pairs of sneakers", I go to tabA, add another pair, switch back to tabB and still see "You have 2 pairs of sneakers". Once the data was sent the cell would briefly show "You have 5 pairs of sneakers" and show 5 cells, then it would correctly update to "You have 3 pairs of sneakers" and the correct amount of cells (I didn't have to switch tabs).
The Notification seemed to work but there was that brief incorrect moment.
I did some research and the most I could find were some posts that said I need to use a semaphore but apparently from several ppl who left comments below they said semaphores aren't meant to be used asynchronously. I had to update my question to exclude the semaphore reference.
Right now I'm running tableView.reloadData() in the completion handler of pullDataFromFirebase().
How do I reload the tableView outside of the observer once it's finished to prevent the duplicate values?
Model:
class SneakerModel{
var sneakerName:String?
}
tabB/ClassB:
ClassB: UIViewController, UITableViewDataSource, UITableViewDelegate{
var sneakerModels[SneakerModel]
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(pullDataFromFirebase), name: NSNotification.Name(rawValue: "pullFirebaseData"), object: nil)
}
override func viewWillAppear(_ animated: Bool){
super.viewWillAppear(animated)
pullDataFromFirebase()
}
func pullDataFromFirebase(){
sneakerRef?.observe( .childAdded, with: {
(snapshot) in
if let dict = snapshot.value as? [String:Any]{
let sneakerName = dict["sneakerName"] as? String
let sneakerModel = SneakerModel()
sneakerModel.sneakerName = sneakerName
self.sneakerModels.append(sneakerModel)
//firebase runs on main queue
self.tableView.reloadData()
}
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sneakerModels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SneakerCell", for: indexPath) as! SneakerCell
let name = sneakerModels[indePath.row]
//I do something else with the sneakerName and how pairs of each I have
cell.sneakerCount = "You have \(sneakerModels.count) pairs of sneakers"
return cell
}
}
}
tabA/ClassA:
ClassA : UIViewController{
#IBAction fileprivate func postTapped(_ sender: UIButton) {
dict = [String:Any]()
dict.updateValue("Adidas", forKey: "sneakerName")
sneakerRef.?.updateChildValues(dict, withCompletionBlock: {
(error, ref) in
//1. show alert everything was successful
//2. post notification to ClassB to update tableView
NotificationCenter.default.post(name: Notification.Name(rawValue: "pullFirebaseData"), object: nil)
}
}
}
In other parts of my app I use a filterDuplicates method that I added as an extension to an Array to filter out duplicate elements. I got it from filter array duplicates:
extension Array {
func filterDuplicates(_ includeElement: #escaping (_ lhs:Element, _ rhs:Element) -> Bool) -> [Element]{
var results = [Element]()
forEach { (element) in
let existingElements = results.filter {
return includeElement(element, $0)
}
if existingElements.count == 0 {
results.append(element)
}
}
return results
}
}
I couldn't find anything particular on SO to my situation so I used the filterDuplicates method which was very convenient.
In my original code I have a date property that I should've added to the question. Any way I'm adding it here and that date property is what I need to use inside the filterDuplicates method to solve my problem:
Model:
class SneakerModel{
var sneakerName:String?
var dateInSecs: NSNumber?
}
Inside tabA/ClassA there is no need to use the Notification inside the Firebase callback however add the dateInSecs to the dict.
tabA/ClassA:
ClassA : UIViewController{
#IBAction fileprivate func postTapped(_ sender: UIButton) {
//you must add this or whichever date formatter your using
let dateInSecs:NSNumber? = Date().timeIntervalSince1970 as NSNumber?
dict = [String:Any]()
dict.updateValue("Adidas", forKey: "sneakerName")
dict.updateValue(dateInSecs!, forKey: "dateInSecs")//you must add this
sneakerRef.?.updateChildValues(dict, withCompletionBlock: {
(error, ref) in
// 1. show alert everything was successful
// 2. no need to use the Notification so I removed it
}
}
}
And in tabB/ClassB inside the completion handler of the Firebase observer in the pullDataFromFirebase() function I used the filterDuplicates method to filter out the duplicate elements that were showing up.
tabB/ClassB:
func pullDataFromFirebase(){
sneakerRef?.observe( .childAdded, with: {
(snapshot) in
if let dict = snapshot.value as? [String:Any]{
let sneakerName = dict["sneakerName"] as? String
let sneakerModel = SneakerModel()
sneakerModel.sneakerName = sneakerName
self.sneakerModels.append(sneakerModel)
// use the filterDuplicates method here
self.sneakerModels = self.sneakerModels.filterDuplicates{$0.dateInSecs == $1.dateInSecs}
self.tableView.reloadData()
}
})
}
Basically the filterDuplicates method loops through the sneakerModels array comparing each element to the dateInSecs and when it finds them it excludes the copies. I then reinitialize the sneakerModels with the results and everything is well.
Also take note that there isn't any need for the Notification observer inside ClassB's viewDidLoad so I removed it.

Cleaning UINavigationController after show in Swift

I have very strange bug, that I didn't have in objective-c.
I have two navigations controller one after another. In first I have UITableView. On cell click I navigate to second controller, and with clicking back button I navigate to first navigation controller. (I don't do anything else.) My memory go up every time that I navigate to second controller but it doesn't go down when I go back.
Code that I have :
First View Controller :
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "segue", sender: self)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue",
let destination = segue.destination as? SecondViewController,
let rowIndex = table.indexPathForSelectedRow {
let item = allItems[rowIndex.section][rowIndex.row]
destination.itemId = segue.id as Int?
destination.coreDataManager = self.coreDataManager
}
}
Second View Controller
override func viewDidLoad() {
super.viewDidLoad()
// reload data
reloadData()
}
private func reloadData() {
// We need database ready to reload data from server
guard coreDataManager != nil else {
print("We try to prepare view, but core data is not ready jet.")
// stop loader
self.loader.stopLoader()
return
}
self.model = Model.init(itemId: itemId! as NSNumber!, managadContext: coreDataManager!.privateChildManagedObjectContext())
}
Model object is object from Objective-c library.
I know that this object is problematic, because if I comment out last row, the step memory graph disappear.
I use same library with same call in previous Objective-C application and I didn't have this memory leak.
I try with :
deinit {
self.model = nil
}
but it didn't help.
How to solve this memory leak, because if you look at the graph it is quite huge. After opening 4 cells I have 187 MB memory used.
EDIT:
I figured that deinit {} is never called.
SUGGESTION
I make coreDataManager as weak var:
weak var coreDataManager: CoreDataManager? // weak property of Second Controller
FULL CODE:
Second controller
import UIKit
import BIModel
class SecondViewController: UIViewController {
// MARK: - Properties
/// This object represent connection to database.
weak var coreDataManager: CoreDataManager?
/// This is a Server object that represent on witch server we try to connect.
var currentServer: Server?
/// This is a cube id that we would like to open in this dashboard.
var itemId: Int? = 1193 // TODO: replace this
/// This is a model object. This object holds all calculations, all data,...
var model : Model?
// MARK: - Life Cicle
override func viewDidLoad() {
super.viewDidLoad()
// reload data
reloadData()
}
private func reloadData() {
// We need database ready to reload data from server
guard coreDataManager != nil else {
print("We try to prepare view, but core data is not ready jet.")
return
}
guard itemId != nil else {
return
}
self.model = Model.init(cubeId: currentCubeId! as NSNumber!, managadContext: coreDataManager!.privateChildManagedObjectContext())
}
einit {
print("DEINIT HAPPENED")
model = nil
}
}
I clean code a little bit. This is now whole code. "DEINIT HAPPENED" is printed, but memory stack is the same.

Resources