简体   繁体   中英

For loop not changing variables

First post here, so just wanted to say hi. Im a starting iOs developer, just for fun though.

Ive been breaking my head over the following code:

for (int n = 0; n <= iterations; n = n + 1) {

   int interval = [[object valueForKey:@"interval"] integerValue];
   NSTimeInterval singeltonTimestamp = interval * n;
   NSLog(@"%d",(int)singeltonTimestamp);

   [skeleton removeObjectForKey:@"date"];
   [skeleton setObject:[[object objectForKey:@"start"] dateByAddingTimeInterval:singeltonTimestamp] forKey:@"date"];
   [yuups addObject:skeleton];
   NSLog(@"adding skeleton");

}

I have an object called skeleton and I am trying to add 4 of them (iterations = 3) with the date increasing with a certain interval. The singeltonTimestamp changes correctly (reading the NSLog output) but the date's for the skeletons are all the same, they dont increase.

"Object" contains a start date and an interval, I set some stuff (like the title) for the skeleton beforehand.

See this output

014-04-12 14:32:38.676 yuup[8397:60b] (
        {
        date = "2014-04-15 18:02:00 +0000";
        title = test;
    },
        {
        date = "2014-04-15 18:02:00 +0000";
        title = test;
    },
        {
        date = "2014-04-15 18:02:00 +0000";
        title = test;
    },
        {
        date = "2014-04-15 18:02:00 +0000";
        title = test;
}
)

Help or tips are much appriciated. Thanks in advance

Try this

skeleton = [NSMutableDictionary dictionary];
[skeleton setObject:[[object objectForKey:@"start"] dateByAddingTimeInterval:singeltonTimestamp] forKey:@"date"];
[yuups addObject:skeleton];

You are adding same object again and again.. You have to make new instance before adding to the NSMutableArray

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM