0

Array replacing previously added object.

array=[[NSMutableArray alloc]init];

NSNumber * index;

AppDelegate * delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
if(delegate.counter!=NumberImages.count)
{
    NSLog(@"%d",delegate.counter);

    imgview.tag=delegate.counter;

    NSLog(@"%ld",(long)imgview.tag);

    index=[[NSNumber alloc]initWithInt:[[firstNo objectAtIndex:imgview.tag]integerValue]];

    //int a=[[firstNo objectAtIndex:imgview.tag]integerValue];

    NSLog(@"%@",index);

    NSLog(@"%@",array);
}

[array addObject:index];

NSLog(@"%@",array);

Problem is that as I insert the object, previously existing object gets replaced.

How may I do this?

2
  • 2
    Where are you initializing array? Post more code. Commented Jul 16, 2013 at 11:30
  • u r adding value only once. so there should be one value only. where is the issue? Is this code in for loop or something? Commented Jul 16, 2013 at 11:35

3 Answers 3

1

Here is the problem:

 array=[[NSMutableArray alloc]init];

Move that into the

-(void)viewDidLoad

or

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

and it should be fixed.

Because you are calling the same function over and over again the array is reinitialized and it will only have 1 value.

Sign up to request clarification or add additional context in comments.

Comments

1

An array, by definition, has one value at each index. If you add 2 objects in the same index, the last insertion overwrites all the past ones. Also, if you create the array each time, every array "deletes" the old one. In fact, you're leaking memory by not releasing it.

2 Comments

as you can see he is adding a value so the default behavior of an NSMutableArray would be creating a list. index is the value not an actual index of the array.
@Vasu Maybe because you alloc init the array each time.
0
if (!array) {
         array=[[NSMutableArray alloc]init];
}

I think it will be helpful to you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.