简体   繁体   中英

swift ios data persistence UIImage

I create a class as following and want to save array: [costCategory] to disk,

class costCategory : NSObject, NSCoding {
var name : String
var defaultValue : Int
var thisMonthsEstimate : Int
var sumOfThisMonthsActuals : Int
var riskFactor : Float
var monthlyAverage : Float
var icon: UIImage!

init (name:String, defaultValue:Int, thisMonthsEstimate:Int, sumOfThisMonthsActuals:Int, riskFactor:Float, monthlyAverage:Float, icon: UIImage) {
    self.name = name
    self.defaultValue = defaultValue
    self.thisMonthsEstimate = thisMonthsEstimate
    self.sumOfThisMonthsActuals = sumOfThisMonthsActuals
    self.riskFactor = riskFactor
    self.monthlyAverage = monthlyAverage
    self.icon = icon
}

// MARK: NSCoding

required init(coder decoder: NSCoder) {
    //Error here "missing argument for parameter name in call
    self.name = decoder.decodeObjectForKey("name") as! String
    self.defaultValue = decoder.decodeIntegerForKey("defaultValue")
    self.thisMonthsEstimate = decoder.decodeIntegerForKey("thisMonthsEstimate")
    self.sumOfThisMonthsActuals = decoder.decodeIntegerForKey("sumOfThisMonthsActuals")
    self.riskFactor = decoder.decodeFloatForKey("riskFactor")
    self.monthlyAverage = decoder.decodeFloatForKey("monthlyAverage")
    self.icon = decoder.decodeObjectForKey("icon") as! UIImage!
    super.init()
}

func encodeWithCoder(coder: NSCoder) {
    coder.encodeObject(self.name, forKey: "name")
    coder.encodeInt(Int32(self.defaultValue), forKey: "defaultValue")
    coder.encodeInt(Int32(self.thisMonthsEstimate), forKey: "thisMonthsEstimate")
    coder.encodeInt(Int32(self.sumOfThisMonthsActuals), forKey: "sumOfThisMonthsActuals")
    coder.encodeFloat(self.riskFactor, forKey: "riskFactor")
    coder.encodeFloat(self.monthlyAverage, forKey: "monthlyAverage")
    coder.encodeObject(self.icon, forKey: "icon")
}

}

I save data in viewController as following:

class ViewController: UIViewController {

@IBOutlet weak var photo: UIImageView!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let defaults = NSUserDefaults.standardUserDefaults()
    let arrayOfObjectsKey = "arrayOfObjectsKey"
    var arrayOfObjects = [costCategory]()
    arrayOfObjects.append(costCategory(name: "Mark", defaultValue: 50, thisMonthsEstimate: 60, sumOfThisMonthsActuals: 70, riskFactor:80, monthlyAverage:90, icon: UIImage(named:"Mark.JPG")!))
    arrayOfObjects.append(costCategory(name: "Mary", defaultValue: 50, thisMonthsEstimate: 60, sumOfThisMonthsActuals: 70, riskFactor:80, monthlyAverage:90, icon: UIImage(named:"Mary.JPG")!))
    var arrayOfObjectsData = NSKeyedArchiver.archivedDataWithRootObject(arrayOfObjects)
    var arrayOfObjectsUnarchivedData = defaults.dataForKey("arrayOfObjectsKey")!
    var arrayOfObjectsUnarchived = NSKeyedUnarchiver.unarchiveObjectWithData(arrayOfObjectsUnarchivedData) as! [costCategory]
    **println(arrayOfObjectsUnarchived[0].icon)**
    **photo.image = arrayOfObjectsUnarchived[0].icon**
}

}

I println(arrayOfObjectsUnarchived[0].icon) find it is nil, cannot get the original image that I save, Why? And use following method to save is good enough? Anyone have other mathod like fileManger? Thanks!!!!

let defaults = NSUserDefaults.standardUserDefaults()

var arrayOfObjectsUnarchivedData = defaults.dataForKey("arrayOfObjectsKey")!

var arrayOfObjectsUnarchived = NSKeyedUnarchiver.unarchiveObjectWithData(arrayOfObjectsUnarchivedData) as! [costCategory]

Storing UIImage in NSUserDefaults is not a good idea.

I would advise to save images in file system and you can store their file system path in your model which can then reside in NSUserDefaults .

However, if you really interested , this is how images are saved in NSUserDefaults :

Writing UIImage :

let imageData = UIImageJPEGRepresentation(image, 1)
let relativePath = "image_\(NSDate.timeIntervalSinceReferenceDate()).jpg"
let path = self.documentsPathForFileName(relativePath)
imageData.writeToFile(path, atomically: true)
NSUserDefaults.standardUserDefaults().setObject(relativePath, forKey: "path")
NSUserDefaults.standardUserDefaults().synchronize()

Reading UIImage :

let possibleOldImagePath = NSUserDefaults.standardUserDefaults().objectForKey("path") as String?

if let oldImagePath = possibleOldImagePath {
    let oldFullPath = self.documentsPathForFileName(oldImagePath)
    let oldImageData = NSData(contentsOfFile: oldFullPath)
    // here is your saved image:
    let oldImage = UIImage(data: oldImageData)
}

EDIT: On OP request

Step 1: Write a method that takes image name and return you image path in file system. Here I am saving files in Documents directory.

- (NSString *)imagePathForImage:(NSString *)iImageName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:iImageName];

    return imagePath;
}

Step 2: Call above method and save image path in your costCategory . I am not writing code for this. I hope you can connect that.

Step 3: Save Image on file system. Pass your image and path you got from above method.

- (void)saveImage:(UIImage *)iImage toPath:(NSString *)iImagePath {
    NSData *imageData = UIImagePNGRepresentation(iImage);
    [imageData writeToFile:iImagePath atomically:NO];
}

Step 4: Finally, when you read your object from NSUserDefaults , fetch the image path property and call below method to get & render the image:

- (UIImage *)imageForPath:(NSString *)iImagePath {
    return [UIImage imageWithContentsOfFile:iImagePath];
}

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