NsMutable 不是 swift 中 [anyobject] 的子类型

NsMutable is not subtype of [anyobject] in swift

我想从 NSUserdefault 获取数组并将其存储到 NsMutableArray 但不幸的是它失败了。

错误

NsMutable is not subtype of [anyobject] in swift

代码

arrayImage  = NSUserDefaults.standardUserDefaults().arrayForKey("ImageArray") as NSMutableArray

我也在尝试像 this post.

那样做向下转换 NSArray->NSString

Apple 文档说:

You can also create an NSArray object directly from a Swift array literal, following the same bridging rules outlined above. When you explicitly type a constant or variable as an NSArray object and assign it an array literal, Swift creates an NSArray object instead of a Swift array.

这里有一个简短的例子:

let imageArray: [AnyObject]? = NSUserDefaults.standardUserDefaults().arrayForKey("ImageArray")
if let array = imageArray{
    var arrayImage: NSArray  = array
}

NSUserDefaults arrayForKey 方法 return 是 AnyObject 的可选数组。如果您希望它是可变的,只需使用 "var".// 示例声明它即可:

var mutableArray  = NSUserDefaults.standardUserDefaults().arrayForKey("ImageArray")

如果你希望它是不可变的,你必须使用 "let".

来声明它
let imutableArray  = NSUserDefaults.standardUserDefaults().arrayForKey("ImageArray")

如果您想确保您的方法在为 userdefaults 设置任何值之前不 return nil,您可以使用 nil 合并运算符“??” return 一个空数组如下:

var mutableArray  = NSUserDefaults.standardUserDefaults().arrayForKey("ImageArray") ?? []

如果您想使用用户默认值存储图像,您必须先将图像转换为 NSData。所以你应该创建一个方法 class 来帮助你:

class Save {
    class func image(key:String, _ value:UIImage) {
        NSUserDefaults.standardUserDefaults().setObject(UIImagePNGRepresentation(value), forKey: key)
    }
    class func imageArray(key:String, _ value:[UIImage]) {
        NSUserDefaults.standardUserDefaults().setObject(NSKeyedArchiver.archivedDataWithRootObject(value), forKey: key)
    }

}

class Load {
    class func image(key:String) -> UIImage! {
        return UIImage(data: ( NSUserDefaults.standardUserDefaults().objectForKey(key) as NSData))!
    }
    class func imageArray(key:String) -> [UIImage]! {
        if let myLoadedData = NSUserDefaults.standardUserDefaults().dataForKey(key) {
            return (NSKeyedUnarchiver.unarchiveObjectWithData(myLoadedData) as? [UIImage]) ?? []
        }
        return []
    }

}

测试

let myProfilePicture1 = UIImage(data: NSData(contentsOfURL: NSURL(string: "http://i.stack.imgur.com/Xs4RX.jpg")!)!)!
let myProfilePicture2 = UIImage(data: NSData(contentsOfURL: NSURL(string: "https://lh6.googleusercontent.com/-Axxzrunya9Y/AAAAAAAAAAI/AAAAAAAAAHo/gsDxk5FlliE/photo.jpg")!)!)!

Save.image("myPic", myProfilePicture1)

let myLoadedPic = Load.image("myPic")

let myImageArray = [myProfilePicture1,myProfilePicture2]

Save.imageArray("myPicArray", myImageArray)

let myLoadedPicArray = Load.imageArray("myPicArray")