在swift 2.0中将NSArray投射到NSMutable Array
问题描述:
当我尝试将nsarray对象插入到可变的swift数组时,我得到了此控制台输出。代码工作正常,但最后,它是抛出一个错误。请帮我解决这个错误。在swift 2.0中将NSArray投射到NSMutable Array
Successfully retrieved 3 scores.
Optional("HmEbbowtxW")
<Events: 0x7b08bdf0, objectId: HmEbbowtxW, localId: (null)> {
CreatedBy = "<PFUser: 0x7b02ed10, objectId: 04jp1ZeBn6>";
EventDescription = test;
EventName = test;
}
Optional("97BzKUxFdE")
<Events: 0x7b08cae0, objectId: 97BzKUxFdE, localId: (null)> {
CreatedBy = "<PFUser: 0x7b02ed10, objectId: 04jp1ZeBn6>";
EventDescription = fg;
EventName = gfg;
}
Optional("QDHkg5tiUw")
<Events: 0x7b08cf80, objectId: QDHkg5tiUw, localId: (null)> {
CreatedBy = "<PFUser: 0x7b02ed10, objectId: 04jp1ZeBn6>";
EventDescription = asdasdasd;
EventName = sdsd;
}
Could not cast value of type '__NSArrayI' (0x228e164) to 'NSMutableArray' (0x228e1c8).
这是我的代码
let query = PFQuery(className:"Events")
query.whereKey("CreatedBy", equalTo:PFUser.currentUser()!)
query.findObjectsInBackgroundWithBlock {
(objects, error) -> Void in
if error == nil {
// The find succeeded.
print("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
self.eventtimelineData.addObject(object)
print(object.objectId)
print(object.description)
}
let array:NSArray = self.eventtimelineData.reverseObjectEnumerator().allObjects
self.eventtimelineData = array as! NSMutableArray
self.tableView.reloadData()
}
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
答
要将NSArray
转换为NSMutableArray
,叫mutableCopy()
和转换为NSMutableArray
:
let a: NSArray = [1, 2.5, "hello"]
let b = a.mutableCopy() as! NSMutableArray
b.addObject(17) // b is [1, 2.5, "hello", 17]
答
您不能从NSArray转换为NSMutableArray。您需要创建一个新的可变阵列:
self.eventtimelineData = array.mutableCopy() as! NSMutableArray
+0
工作。谢谢! –
工作。谢谢! –