从.plist检索的Objective-C样式在Swift中不起作用? [英] Objective-C style retrieving from .plist not working in Swift?
问题描述
每当通过以下方法加载视图时,我就是在Objective-C的.plist中检索数据-
I was was retrieving data in a .plist in Objective-C whenever my view loaded by the following method -
@interface ListTableViewController ()
@end
@implementation ListTableViewController
NSArray *dict;
-(void)viewDidAppear:(BOOL)animated
{
NSString *arr= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
arr=[arr stringByAppendingPathComponent:@"datalist.plist"];
if ([[NSFileManager defaultManager]fileExistsAtPath:arr])
{
dict=[NSArray arrayWithContentsOfFile:arr];
NSLog(@"%@",dict);
}
[self.tableView reloadData];
}
现在,对于Swift我正在做的事情与-
Now for Swift I am doing the same thing as -
class ListTableViewController: UITableViewController{
var arr = NSArray()
var plistfinalpath = String()
override func viewDidAppear(animated: Bool){
let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true)[0]
plistfinalpath = path.stringByAppendingString("/login.plist")
print(plistfinalpath)
print("time of appearing\(arr)")
arr = NSArray(contentsOfFile: plistfinalpath)!
self.tableView.reloadData()
}
}
但是,由于我必须在第一次启动应用程序时在plist为空时解开arr = NSArray(contentsOfFile: plistfinalpath)!
行中的值,因此数组为空,并且由于我将其解包,因此显示错误.那么如何实现目标C中的工作呢?
But since I have to unwrap the value in the line arr = NSArray(contentsOfFile: plistfinalpath)!
when the plist is empty when the app is launched for the first time the array is empty and since I am unwrapping it, it shows an error. So how can I achieve what I was doing in objective C?
推荐答案
只需将arr
变量定义为可选变量,如下所示:
var arr:NSArray? = NSArray()
Just define your arr
variable as optional, like this :
var arr:NSArray? = NSArray()
将变量定义为非可选变量时,不能将其设置为nil
.您使用的NSArray
初始化程序定义为public convenience init?(contentsOfFile path: String)
-?
表示它实际上可以返回nil
.当您使用!
时,您将强制解开该值,当该值为nil
时,将导致运行时崩溃.
When a variable is defined as non optional, you cannot make it nil
. The NSArray
initializer you used is defined as public convenience init?(contentsOfFile path: String)
- the ?
means, that it can in fact return a nil
. When you used !
, you force unwrapped the value, which results in runtime crash when the value is nil
.
与往常一样,您可以在文档中阅读更多内容
As always, you can read more in the docs
或者,您可以执行以下操作:
Alternatively, you can do something like this :
if let tempArr = NSArray(contentsOfFile: plistfinalpath) {
arr = tempArr
}
这样,您无需将arr
定义为可选,而仅在文件内容不为空时分配给它.
This way, you don't need to have your arr
defined as optional and will only assign to it, when the contents of file where not empty.
这篇关于从.plist检索的Objective-C样式在Swift中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!