如何添加两个可变数组?迅速

时间:2016-06-23 09:53:25

标签: ios swift nsmutablearray nsarray

在我的应用中,我想实现下拉刷新。因此,当滚动视图向下滚动其加载更多数据。现在第一次加载页面时我将数据保存在 videoArray 数组中,当向下滚动时我得到 videoArray2 数组中的数据,那么如何添加 videoArray2的值 videoArray ?两者都是nsmuttablearray。

这是我的代码:

var videoArray : NSMutableArray = NSMutableArray()
var videoArray2 : NSMutableArray = NSMutableArray()

我第一次在这个数组中存储值

self.videoArray = (response.result.value)?.valueForKey("posts") as! NSMutableArray

第二次我在这个数组中存储了值

self.videoArray2 = (response.result.value)?.valueForKey("posts") as! NSMutableArray

这就是我试图追加

的方式
for enumerator in self.videoArray2
{
    self.videoArray.addObject(enumerator)
}

但它的投掷错误如

  

***由于未捕获的异常终止应用程序' NSInternalInconsistencyException',原因:' - [__ NSCFArray insertObject:atIndex:]:发送到不可变对象的变异方法'

那我怎么解决这个问题呢?

4 个答案:

答案 0 :(得分:5)

以Swift方式这么简单

    server {
        listen 443;
        server_name   example.com;

        ssl on;
        ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
        ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    }

或者像你所声明的那样

var array : [AnyObject] = [AnyObject]()
var array1 : [AnyObject] = [AnyObject]()
//Add array like this
array.appendContentsOf(array1)

OR

var videoArray : NSMutableArray = NSMutableArray()
var videoArray2 : NSMutableArray = NSMutableArray()
//Add like this
videoArray.addObjectsFromArray(videoArray2 as [AnyObject])

答案 1 :(得分:4)

let videoArray = (response.result.value)?.valueForKey("posts") as! NSArray
self.videoArray = NSMutableArray(array:videoArray)

和第二个数组相同

答案 2 :(得分:2)

//(response.result.value)?. valueForKey(“posts”)返回NSArray,因此你必须将它带入一个数组对象,然后你可以将所有对象传递给你的mutablearray < / p>

let array = (response.result.value)?.valueForKey("posts") as! NSMutableArray
self.videoArray = NSMutableArray(array:array)

//从videoArray2添加对象到videoArray

self.videoArray.addObjectsFromArray(self.videoArray2)

答案 3 :(得分:0)

Replace this line code 

self.videoArray = (response.result.value)?.valueForKey("posts") as! NSMutableArray

With 

let vidArray = response.result.value)?.valueForKey("posts") as! NSArray;
self.videoArray = vidArray.mutableCopy() as! NSMutableArray


First Line of code get the data from server as NSArray and later second line creates a mutable copy of that array.

Now Code below Run as expected.
for enumerator in self.videoArray2
{
    self.videoArray.addObject(enumerator)
}

Now you can add objects to the mutable copy of the videoArray.