I have two classes both for different UIViewController, in one of the classes i have 3 arrays, and i have added those arrays to a NSUserdefaults, now i want to call those/use those arrays in the other class, how do i do that?
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(name, forKey: "ThisContainsName")
userDefaults.setObject(surname, forKey: "ThisContainsSurname")
userDefaults.setObject(money, forKey: "ThisContainsBudget")
userDefaults.synchronize()
Just use arrayForKey to get the arrays:
var yourNames = NSUserDefaults.standardUserDefaults().arrayForKey("ThisContainsName")
var yourSurnames = NSUserDefaults.standardUserDefaults().arrayForKey("ThisContainsSurname")
var yourMoneys = NSUserDefaults.standardUserDefaults().arrayForKey("ThisContainsBudget")
Related
I have a tableview cell which consist of one menu button icon -> menutitle -> eyeImage. How do I reorder the cell and save the state of the cell after reorder? I have two arrays for menuicons and menutitles.
My two arrays:-
var menuTitlesArr = ["Portfolio","Moves & Alerts","Market Analysis","Chats","]
var menuIconsArr = ["portfolio","cal","news","chat","more"]
My screenshot:-
image for my tableview cell:
I think that you can start using UserDefault, you can save the array using it
import Foundation
// Access Shared Defaults Object
let userDefaults = UserDefaults.standard
// Create and Write Array of Strings
let array = ["One", "Two", "Three"]
userDefaults.set(array, forKey: "myKey")
// Read/Get Array of Strings
let strings = userDefaults.object(forKey: "myKey")
Then, when you change the cells order, set it again
let array = ["Two", "One", "Three"]
userDefaults.set(array, forKey: "myKey")
For something more advanced I like to use the Realm for local storage
I'm trying to save 2d array data using userdefaults, but i'm getting this error Cannot convert value of type '[[String]]' to expected argument type 'String' here is my code
var tempQuestion2 = [tempQuestion]
if var tempData = UserDefaults.standard.stringArray(forKey: "tempData")
{
tempData.append(tempQuestion2)
tempQuestion2 = tempData
}
UserDefaults.standard.set(tempQuestion2, forKey: "tempData")
tempQuestion is a string array with data like [“9+1=10”, “5+4=9”] and i want tempQuestion2 to be [["9+1=10, "5+4=9"], ["3+4=7", "4+1=5"]] I'm guessing my issue is at UserDefaults.standard.stringArray. My question is different from the link because that question is about dictionary not array of array.
There's no problem saving and loading arrays of arrays to UserDefaults, to save your data use:
UserDefaults.standard.set(tempQuestion2, forKey: "tempData")
To read back (and update) the array of arrays use:
// Assuming tempQuestion is [String]
if var tempData = UserDefaults.standard.array(forKey: "tempData") as? [[String]] {
tempData.append(tempQuestion2)
UserDefaults.standard.set(tempData, forKey: "temp")
}
i'm updating my app to Swift 2.. lots of errors uff.. anyway i'm trying to read a store array in NSuserDefaults, in swift 1 worked but now i get nil error with EXC_Breakdown. i don't know how to fix that...
this is how i read it:
var DescriptionArray = save.objectForKey("NewsDescriptions")! as! NSArray
this i how i save it (Description is the array):
var SaveDescription = save.setObject(Description, forKey: "NewsDescriptions")
save.synchronize()
Here is an example of how you can store data into NSUserDefault in Swift 2.0. It is very similar to Objective-C concept, only different syntax.
Initialize your NSUserDefault Variable:
let userDefaults = NSUserDefaults.standardUserDefaults()
Initialize what type of data to save: In your case you used objectForKey, even though that should work, it's better to be more specific about your code.
var DescriptionArray = userDefaults.arrayForKey("NewsDescriptions")
Save your data:
userDefaults.setObject(Description, forKey: "NewsDescriptions")
Then you can synchronize to process the saving faster.
userDefaults.synchronize()
Here is an example with Swift 2:
func saveArray(value: NSArray) {
NSUserDefaults.standardUserDefaults().setObject(value, forKey:"NewsDescriptions")
NSUserDefaults.standardUserDefaults().synchronize()
}
func readArray() -> NSArray {
return NSUserDefaults.standardUserDefaults().arrayForKey("NewsDescriptions")!
}
Well I have been making a test app to continue my swift learning, today I came across a problem.
Basically I have a tableview and a detailview. For my tableview file I have some data that I am currently passing to the detailview, like the name that goes on the navigation bar, one image and some text, this data is stored in arrays on my tableview file, I use "prepareforsegue" to pass this information:
var names = ["name1","name2","name3"]
detailViewController.detailName = names[indexPath.row]
Then in my detailViewController I have variables set for that:
var detailName: String?
Then I use this for stuff, example: naming my navigation bar or setting an image in detailView:
navigationItem.title = detailName!
Now, what I dont get how to do is pass a whole array of information to a variable in my detailViewController. What I want to do is pass an array of images to use it on my detailView. I want to be able to iterate through the array of images with a button, I know how to set that up but I just need to know how to pass the array, right now I am just passing one of the values(one name, one image etc...)
Thanks for the help in advance.
It's not so different from what you have done.
Just add field for images in detailViewController, and then pass images using it. Images could be represented in [UIImage]. However, [String] can be also used for local filenames, and [NSURL] can be used for remote image urls.
code:
In DetailViewController:
var images: [UIImage]? // or var images: [UIImage] = []
In prepareForSegue:
detailViewController.images = YourImages
You seem to be asking for one of two things:
A UIImage array, which you can declare using var imageArray : [UIImage] = [] and then append whatever images you want to pass.
Alternatively, you can pass in a [AnyObject] array and cast its elements to a UIImage or String by doing
var objectArray : [AnyObject] = []
objectArray.append("test")
objectArray.append(UIImage(named: "test.png")!)
if let s = objectArray[0] as? String {
// Do something with the string
}
if let i = objectArray[1] as? UIImage {
// Do something with the image
}
if let s = objectArray[1] as? String {
// The above cast fails, this code block won't be executed
} else {
// ... but this one will
}
in the table view controller file:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get reference to the destination view controller
var detailVC = segue.destinationViewController as! DetailViewController
var detailImages: Array<UIImage> = []
detailImages.append(UIImage(named: "pup.png")!)
detailImages.append(UIImage(named: "cutepuppy.png")!)
detailVC.detailImages = detailImages;
}
and in the detail file:
var detailImages: Array<UIImage>?
I'm trying to get my head around Swift (after being relatively competent with Obj-C) by making a small app. I would like to use NSUserDefaults to persistently save a small amount of data but I am having problems.
I initialise an empty array of tuples like this:
var costCategoryArray: [(name:String, defaultValue:Int, thisMonthsEstimate:Int, sumOfThisMonthsActuals:Int, riskFactor:Float, monthlyAverage:Float)]=[]
When the array has an entry, I want to save the array to NSUserDefaults with standard Swift code such as this:
NSUserDefaults.standardUserDefaults().setObject(costCategoryArray, forKey: "financialData")
NSUserDefaults.standardUserDefaults().synchronize()
I get an error saying that the tuple array doesn't conform to the AnyObject class. So I tried to turn it into NSData:
var myNSData: NSData = NSKeyedArchiver.archivedDataWithRootObject(costCategoryArray)
var myUnarchivedData: Array = NSKeyedUnarchiver.unarchiveObjectWithData(myNSData)
...but I get the same error during the conversion to NSData. The object being held by my array doesn't conform to AnyObject. I've also tried at each stage to make it immutable by using:
let immutableArray = costCategoryArray
Ive also tried creating a class instead of using tuples which I understood would make it comply with AnyObject:
class costCategory : NSObject {
var name : String
var defaultValue : Int
var thisMonthsEstimate : Int
var sumOfThisMonthsActuals : Int
var riskFactor : Float
var monthlyAverage : Float
init (name:String, defaultValue:Int, thisMonthsEstimate:Int, sumOfThisMonthsActuals:Int, riskFactor:Float, monthlyAverage:Float) {
self.name = name
self.defaultValue = defaultValue
self.thisMonthsEstimate = thisMonthsEstimate
self.sumOfThisMonthsActuals = sumOfThisMonthsActuals
self.riskFactor = riskFactor
self.monthlyAverage = monthlyAverage
}
}
But the new error is:
"Property list invalid for format: 200 (property lists cannot contain objects of type 'CFType')"
What is the problem with an array of tuples? Why can't I store an array of class objects? I feel like I need some expert advice as so far everything I try to do with Swift is pretty much incompatible...
Thanks!
Anything you are archiving to NSData and back needs to implement the NSCoding protocol. I found that in addition, my Swift class had to extend NSObject. Here is a quick example of a Swift class that encodes and decodes:
class B : NSObject, NSCoding {
var str : String = "test"
required init(coder aDecoder: NSCoder) {
str = aDecoder.decodeObjectForKey("str") as String
}
override init() {
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(str, forKey: "str")
}
}
// create an Object of Class B
var b : B = B()
// Archive it to NSData
var data : NSData = NSKeyedArchiver.archivedDataWithRootObject(b)
// Create a new object of Class B from the data
var b2 : B = NSKeyedUnarchiver.unarchiveObjectWithData(data) as B
value of "financialData" should be in quotes:
NSUserDefaults.standardUserDefaults().setObject("costCategoryArray", forKey: "financialData")
NSUserDefaults.standardUserDefaults().synchronize()