开发者

Add same NSDictionary to NSMutableArray multiple time issues

My countTextView returns 3. I have verified that the the for loop does get called 3 times. 1 inside the if statement and 2 on the else. But when I try to NSLog out the array, it only contain 1 object. Why is that so?

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; 
for (int i = 1; i <= [countTextView.text开发者_开发问答 intValue]; i++) {
    NSLog(@"called %i times", i);
    // prepare keys and object needed to created a dic to save booking info.
    NSArray *keys = [NSArray arrayWithObjects:@"PickUpAddress", @"Time", nil];
    NSArray *objects = [NSArray arrayWithObjects:[addressTextView.text stringByReplacingOccurrencesOfString:@"\n" withString:@" "], date , nil];
    NSDictionary *statusInfoDic = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    if ([prefs objectForKey:@"StatusInfoArray"] == nil) {
        NSArray *statusInfoArray = [NSArray arrayWithObject:statusInfoDic];
        [prefs setObject:statusInfoArray forKey:@"StatusInfoArray"];
        [prefs synchronize];
        NSLog(@"nil called on %i", i);
    }
    else {
        NSMutableArray *currentStatusInfoArray = [NSMutableArray arrayWithArray:[prefs objectForKey:@"StatusInfoArray"]];
        [currentStatusInfoArray addObject:@"statusInfoDic"];
        [prefs synchronize];
        NSLog(@"not nil called on %i ", i);
    }
}
NSLog(@"statusInfoArray : %@", [prefs objectForKey:@"StatusInfoArray"]);


In your else section you are creating an 'arrayWithArray'. This statement is giving you a handle to a newly created (duplicate) array object - so you are adding to this new array - but you are not saving the result anywhere - so you are adding to an array that is never used.

Change this line:

NSMutableArray *currentStatusInfoArray = [NSMutableArray arrayWithArray:[prefs objectForKey:@"StatusInfoArray"]];

to this instead:

NSMutableArray *currentStatusInfoArray = [prefs objectForKey:@"StatusInfoArray"];

And I think you will find everything is better.

EDIT:

Actually the above won't work because pref's will always give you back an immutable array. What you will need to do is instead replace your prefs status info array each time:

So ignore the above and instead:

Replace

[currentStatusInfoArray addObject:@"statusInfoDic"]; 

with:

[currentStatusInfoArray addObject:@"statusInfoDic"]; 
[prefs setObject:currentStatusInfoArray forKey:@"StatusInfoArray"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜