如何在 iOS 中添加和获取 .plist 中的值
我正在实现一个基于网络服务的应用程序。因为我需要在 .plist 中添加一个字符串作为属性,并且只要在代码中需要,我就需要从 .plist 中获取值。
I am implementing a application based on web services. In that I need to add a string as property in .plist and I need to get the value from the .plist whenever I need in the code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是一个代码示例:
Here is a code sample:
或者你也可以使用以下
or you can use following also
从 plist 获取非常简单。
如果你想向 plist 添加一些东西,也许你可以在这里找到答案:
如何在plist中写入数据?
但是如果你只想在您的应用程序中保存一些消息,NSUserDefaults 是更好的方法。
Get from plist is very simple.
If you want to add something to a plist, maybe you can find the answer here:
How to write data in plist?
But if you only want save some message in you app, NSUserDefaults is the better way.
你不能这样做。任何捆绑包(无论是 iOS 还是 Mac OS)都是只读的,您只能读取它,不能创建文件、写入文件或对捆绑包中的文件执行任何操作。这是苹果安全功能的一部分。您可以使用 NSDocumentsDirectory 来编写和阅读应用程序所需的内容
You can not do this. Any Bundle wether it is iOS or Mac OS is readonly, you can only read to it and you can't create files, write or do anything with the files in a bundle. This is part of the Security features of apple. You can use the NSDocumentsDirectory to writr and read your stuff you need for your app
斯威夫特,
我知道这是 12 年前提出的问题。但这是通过谷歌提出的第一个SO问题。因此,为了节省每个人的时间,以下是如何在 swift 中执行此操作:
请注意,这两个函数使用略有不同的方法来访问 plist。但实际上它们几乎是一样的。
理论上可能没有plist。因此 infoDictionary 是可选的。但在这种情况下,第一个方法也会返回一个意外的值,从而导致错误。
Apple 指出的一个实际差异:
参考
Bundle.main.object(forInfoDictionaryKey: "BASE_URL")
Swift
I know this was asked 12+ years ago. But this was the first SO question to come up via google. So to save time for everyone, here is how to do this in swift:
Notice the 2 functions use slightly diffrent methods to access the plist. But in effect they are almost the same.
In theory there might not be a plist. Hence infoDictionary is optional. But in this case the first method will also return an unexpected value, resulting in an error.
One actual difference as noted by Apple:
Refering to
Bundle.main.object(forInfoDictionaryKey: "BASE_URL")