Ega Setya Putra
Ega Setya Putra

Reputation: 1695

How to add new object to NSMutableArray?

I wonder how can I add an new item on NSMutableArray in each button click. I already did addObject("something") in button action. The result is always something the object.count still 1. What I want is in each click the object on NSMutableArray adding.

Right now the result I get is like below: This when I clicked three times

(something)(something)(something)

But the result that I want is like this

(something,something,something)

when I clicked 5 times

(something,something,something,something,something)

... and so on

Here is my code

@IBAction func press(sender: UIButton) {
    var mutar : NSMutableArray = NSMutableArray()
    mutar.addObject("something")
    println(mutar)
}

Upvotes: 0

Views: 863

Answers (5)

iDhaval
iDhaval

Reputation: 3205

Problem is that when you click the button it will create new NSMutableArray

Create instance variable

var mutar : NSMutableArray = NSMutableArray()

@IBAction func press(sender: UIButton) {

      mutar.addObject("something")


     println(mutar)
}

Upvotes: 0

Vishal Deshai
Vishal Deshai

Reputation: 21

Here is my objective c code snippet:

array = [NSMutableArray arrayWithArray:[[[NSUserDefaults standardUserDefaults] valueForKey:string] componentsSeparatedByString:@","]];
if (array==nil)
    array = [NSMutableArray arrayWithObjects:crctId, nil];
else if (![array containsObject:crctId]){
    flag = YES;
    if(crctId!=nil)
    {
        [array addObject:crctId];
    }
}

Upvotes: 0

Sujay
Sujay

Reputation: 2520

Create a global array and allocate memory only once either from viewDidLoad or viewWillAppear or viewDidAppear, In your case on every click you are allocating memory to that array then adding that object into array. So initialize and allocate memory only once and than add object on button click, you will get your expected result.

Upvotes: 0

Eyeball
Eyeball

Reputation: 3317

You need to add your array as an instance variable of your class.

At the top of your class, put:

var array = NSMutableArray()

You are currently initializing an array and adding one object to it, each time you click the button, hence you only have one object each time.

Upvotes: 0

Utsav Parikh
Utsav Parikh

Reputation: 1206

It is because you are allocating the array every time whenever you press the button. It will always get reduced to count 0 on allocation.

Keep this line out of the IBAction method and add it to viewDidLoad():

var mutar : NSMutableArray = NSMutableArray()

Upvotes: 1

Related Questions