简体   繁体   中英

Is NSMutableArray instance, optional by default in SWIFT?

I have been using this following thing to do my plist and save data and display contents of plist in a Table View. I am using a NSMutableArray to fetch the contents of the array and display it in the table view . VC1 is my table view & VC2 is my EnterDetail VC So I have declared my code as follows -

class ListTableViewController: UITableViewController
{
var arr = NSMutableArray()

    var plistfinalpath = String()

    override func viewDidLoad()
    {
        super.viewDidLoad()


    }


    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()

    }
    override func viewDidAppear(animated: Bool)
    {


            let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true)[0]
            plistfinalpath = path.stringByAppendingString("/login.plist")
            print(plistfinalpath)
        arr = (NSMutableArray(contentsOfFile: plistfinalpath))!
            print("time of appearing\(arr)")

       /* if let temparray = NSMutableArray(contentsOfFile: plistfinalpath)
        {
            arr = temparray
        }*/




        self.tableView.reloadData()

    }

So as you can see that I have declared a 'arr' as a NSMutableArray type and it is not optional. And when I use in my didappear() the compiler forces me to force unwrap it. Why is that so why does it happens evenif I have declared 'arr' as non optional? And here comes the real problem whenever I run my app for the first time the plist is empty implies 'arr' is also empty. And since I have used forced unwrapping my app crashes due to fatal error. And if I uncomment my commented line in the above code, the if let part, it works fine . So any suggestions. Thanks.

there is no trouble with your NSMutableArray.

var arr = NSMutableArray()

create non optional instance of an array. so far, so good ... An expression

NSMutableArray(contentsOfFile: plistfinalpath)

can return nil, so it returns the optional value. Here you try to create another instance of NSMutableArray and assign the result to your var arr.

A mutable array containing the contents of the file specified aPath. Returns nil if the file can't be opened or if the contents of the file can't be parsed into a mutable array.

Probably the best way for you is something like

import Foundation
var arr = NSMutableArray(contentsOfFile: "somePath") ?? NSMutableArray()

Here your variable is guaranty to have the default value (an empty instance of NSMutableArray) if the file does not exist yet (or other failure happened)

To resolve your fatal error check your file exist or not :-

   //Check whether your file exist or not
 let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true)[0]
        plistfinalpath = path.stringByAppendingString("/login.plist")
    if NSFileManager.defaultManager().fileExistsAtPath(plistfinalpath)
    {
        arr = (NSMutableArray(contentsOfFile: plistfinalpath))!
    }

Declare it like

var arr : NSMutableArray = []

// Or

var arr : NSMutableArray!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM