为什么NSMutableArray在视图发生变化时没有保存数据?

时间:2015-04-30 23:26:55

标签: ios cocoa-touch nsmutablearray

我有一个tableviewcontroller(Stops),它显示了一个停止列表(stopsArray),用户可以在其中标记一个特定的Stop,就像他的收藏夹一样。触摸UIImage后,停止保存在NSMutableArray(myStopsMArray)上。直到这里一切都好。但是当我离开那个视图控制器时,我失去了NSMutableArray的所有数据。这是我的代码:

Stops.h:

#import <UIKit/UIKit.h>

 @interface Stops : UIViewController <UITableViewDataSource, UITableViewDelegate>;

@property (weak, nonatomic) IBOutlet UITableView *stopsTable;

@property (nonatomic, retain) NSArray *stopsArray;

@property (nonatomic, retain) NSMutableArray *myStopsMArray;

@end

Stops.m:

#import "Stops.h"
#import "Stop.h"
#import "MyStops.h"
#import "Global.h"

@interface Stops ()

@end

 @implementation Stops

@synthesize stopsArray, myStopsMArray, stopsTable;

- (void)viewWillAppear:(BOOL)animated
{
    if (!self.myStopsMArray) {
        self.myStopsMArray = [[NSMutableArray alloc] init];
    }

}


- (void) addToFavourites:(id)sender {

    UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender;

    NSInteger tag = gesture.view.tag;

    NSIndexPath *tagIndex = [NSIndexPath indexPathForItem:tag inSection:0];

     UITableViewCell *cell = [stopsTable cellForRowAtIndexPath:tagIndex];

     if ([cell.imageView.image isEqual: [UIImage imageNamed:@"star_filled_white.png"]]) {
        // Add Stop to favourites

        [self.myStopsMArray addObject:[stopsArray objectAtIndex:tag]];
        cell.imageView.image = [UIImage imageNamed:@"star_filled_yellow.png"];

    } else {
    // Delete Stops from favourites

        [self.myStopsMArray removeObject:[stopsArray objectAtIndex:tag]];
        cell.imageView.image = [UIImage imageNamed:@"star_filled_white.png"];
    }

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:self.myStopsMArray forKey:@"myStopsMArray"];
    [userDefaults synchronize];


    NSArray *savedData = [userDefaults objectForKey:@"myStopsMArray"];

    NSLog(@"%@", savedData);

}

@end

非常感谢你。

1 个答案:

答案 0 :(得分:0)

如果有人和我在同一个地方,这就是神奇的线 - 已经纠正了 - :

Stops.m:

if ([savedData containsObject: [stopsArray objectAtIndex:index]]) {
    ...
}

不要忘记先前申报NSUserDefaults:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSArray *savedData = [userDefaults objectForKey:@"myStopsMArray"];