After adding element in NSMutableArray previous elements gets replaced - ios

I'm working on app in which I want to create array with number of NSDictionary's. When i'm trying to add NSMutableDictionary in NSMutableArray, previously added elements of that array get replaced. I don't know what is happening. Code as follows:
var paynowArray = NSMutableArray()
let tempDict = NSMutableDictionary()
for i in 0...selectedEmenetsArray.count-1 {
tempDict.removeAllObjects()
tempDict.setValue(selectedIdAry[i], forKey: "serviceId")
tempDict.setValue(selectedAmountAry[i], forKey: "serviceAmount")
paynowArray.add(tempDict)
}
print(paynowArray)
While printing array last added NSMutableDictionary printed n times.
Thanks in advance.

Create tempDict inside the for loop. You should allocate dictionary for every element. Else you are replacing the same memory location value every times.
var paynowArray = NSMutableArray()
for i in 0...selectedEmenetsArray.count-1 {
var tempDict = NSMutableDictionary()
tempDict.setValue(selectedIdAry[i], forKey: "serviceId")
tempDict.setValue(selectedAmountAry[i], forKey: "serviceAmount")
paynowArray.add(tempDict)
}
print(paynowArray)

Should be inside the loop..
let tempDict = NSMutableDictionary()

Related

Tableview gets filled correctly sometimes and most of the times it is empty

I have a question regarding loading data from a database (a list of dishes) into a tableview. Now follows the piece of code where I think maybe something goes wrong:
//get the data from database and put it in dishesJSON
let dishesJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
//getting the JSON array dishes from the response
let dishes : NSArray = dishesJSON["dishes"] as! NSArray
//create temporary array
var temp : NSArray
//create temporary variable of type string
var tempstring : String
for i in 0 ..< dishes.count {
temp = dishes[i] as! NSArray
tempstring = temp[1] as! String
self.arrayOfDishes.append(tempstring)
}
print(self.arrayOfDishes)
Now when I run the app, I always see that it prints the list of dishes correctly in the console. But the weird thing is that sometimes the tableview is empty and sometimes the tableview is correctly filled with the list of dishes. The weird thing is that when I filled the tableview with a predefined list of strings, it always worked, but now it does not seem to work sometimes. So I am pretty sure there is no problem in how I defined the table and fill it with an array of strings. I think the problem is maybe somewhere here. If the problem is not in here, I can look further to find the culprit. Thanks!
Don't know if you grab this from a web Service or not , but try
for i in 0 ..< dishes.count {
temp = dishes[i] as! NSArray
tempstring = temp[1] as! String
self.arrayOfDishes.append(tempstring)
}
DispatchQueue.main.async { // as it may be in a background thread
self.tableView.reloadData()
}

Swift NSMutableArray add one more array

The Problem is First time I get data from WebServices so I have show this data on TableView Then user scroller down tableview then again call WebSevices and add this data to again in array
but when I try to add data again in nsmutable type array app is crashing
Here is my code. Any solution?
1st time Data load is Working
var ary_mutable: NSMutableArray!
ary_mutable = NSMutableArray()
ary_mutable=jsonResult as AnyObject as! NSMutableArray
self.tbl_T.reloadData();
self.tbl_T.delegate=self;
self.tbl_T.dataSource=self;
2nd Time data load and add with old array not Working
var myArray :NSArray!
myArray = jsonResult as AnyObject as! NSArray
ary_mutable.addObject(myArray.objectAtIndex(0))
Got This Error
[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'
I have Try this code also But Not Working
ary_mutable.addObject(myArray)
You should create a mutable array from immutable. This:
ary_mutable=jsonResult as AnyObject as! NSMutableArray
does not do it, it is just a static cast from one type to another. You have to construct a new NSMutableArray and then fill it with required values.
Change your code to
var ary_mutable = NSMutableArray()
// everytime you receive a new data
ary_mutable.addObjectsFromArray(jsonResult as! [AnyObject])
replace this code:
var myArray :NSArray!
myArray = jsonResult as AnyObject as! NSArray
ary_mutable.addObject(myArray.objectAtIndex(0))
with this code:
var myArray : NSMutableArray!
myArray = jsonResult as AnyObject as! NSMutableArray
ary_mutable.addObjectsFromArray(myArray as [AnyObject]);

Swift Array addObjects to NSMutableArray

I have a Swift Array and I want to add all the objects inside to NSMutableArray
let stringName: String = "Something"
let stringNameSeperated = Array(logoName)
let mutableStringName: NSMutableArray = NSMutableArray(array: stringNameSeperated)
How can I do that?
I'm not really sure what you wanted to archive, but if you just wanted a Swift.Character sequence array, here's a simpler way without even the Array() process: (Notice that the result was casted into String. If you want Character, you will have to modify the code a bit.)
let stringName: String = "Something"
let mutableStringName: NSMutableArray = NSMutableArray(array: map(stringName) { String($0) } )
And from my understanding, you no longer have to case between Swift Array and Objective-C Array, you can use them interchangeably. Also, you can pass a Swift Array to a parameter that expected to be NSArray without problem in Swift 1.x as well.

iOS Swift Error: Execution was interrupted, reason : signal SIGABRT

I am trying to execute the following code in a playground. Fairly, I am treating both variables bm and ul equally but error shows only at ul
import UIKit
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject([], forKey: "bookmarks")
defaults.setObject([], forKey: "urls")
var bm : NSMutableArray = defaults.valueForKey("bookmarks") as NSMutableArray
var ul : NSMutableArray = defaults.valueForKey("urls") as NSMutableArray
bm.addObject("Google") //--->Works
ul.addObject("http://google.com") //--->Oops, No
I can't tell you why the first works and the second doesn't - it is probably just a quirk of playgrounds, timing and a delay in persisting NSUserDefaults to disk.
Your problem, however, is that valueForKey (and you should use objectForKey) returns immutable objects - so bm and ul will actually be NSArray instances and you can't simply cast them to NSMutableArray. You get a crash when you try to do so and mutate the object.
You need to create a mutable copy of your array.
var bm=defaults.objectForKey("bookmarks") as NSArray?
if bm != nil {
var bmCopy=bm!.mutableCopy() as NSMutableArray
bmCopy.addObject("Google")
defaults.setObject(bmCopy, forKey:"bookmarks")
}

Saving NSMutableArray with NSUserDefaults in Swift Returns Nil

I have a NSMutableArray. Here is how I save it with NSUserDefaults:
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(downloadedFile as NSMutableArray, forKey: "myKey")
And here how I retrieve it:
var downloadedFilesFromUserDefaults:NSMutableArray = defaults.objectForKey("myKey") as NSMutableArray
take look at this and try to save you array like this! as this worked perfectly!
var arr:NSMutableArray = NSMutableArray(objects: "ASD","aSd")
NSUserDefaults.standardUserDefaults().setObject(arr, forKey: "Array")
NSUserDefaults.standardUserDefaults().synchronize()
on button click
NSLog("%#", NSUserDefaults.standardUserDefaults().objectForKey("Array") as NSMutableArray)
It looks like swift somehow release my object i needed to make sure that my object is not nil.

Resources