1
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.carMakes = [[NSArray alloc]
                     initWithObjects:@"Chevy",
                     @"BMW",
                     @"Toyota",
                     @"Volvo",
                     @"Smart", nil];

    self.carModels = [[NSArray alloc]
                      initWithObjects:@"Volt",
                      @"Mini",
                      @"Venza",
                      @"S60",
                      @"Fortwo", nil];

    self.carImages = [[NSArray alloc]
          initWithObjects:@"chevy_volt.jpg",
                      @"mini_clubman.jpg",
                      @"toyota_venza.jpg",
                      @"volvo_s60.jpg",
                      @"smart_fortwo.jpg", nil];
}

上面的代码填充在表格视图中。我想让用户选择一些汽车,这样汽车的名称、型号和图片将保存在另一个列表中。我不知道应该在哪里保存用户选择的数据以及如何保存。我希望稍后能够在 TableView 上显示用户选择的汽车列表。

  • 我知道如果我想保留新创建的列表,我需要将选择的信息转换为 plist 文件或类似的文件,但我不确定在此之前将数据保存在哪里。
4

2 回答 2

2

您可以为此使用数组或字典。但更好的方法是创建一个模型类数组来保存这些数据。这最适合MVC 架构。例如,您可以创建一个模型类,Car它具有属性、NSString *makeNSString *modelUIImage *image其中声明。如果要填充表格视图,则需要创建这些汽车模型对象的数组,并在委托方法中使用它来填充单元格。如果要持久化数据,可以将其转换为字典形式,然后将其存储为 plist。有关更多详细信息,请查看ray wenderlich 的本教程

一个典型的模型对象看起来像,

@interface Car : NSObject {}
@property (nonatomic, retain) NSString *make; 
@property (nonatomic, retain) NSString *model;
@property (nonatomic, retain) UIImage *image;
@end

创建模型对象数组,

Car *carObject = [[Car alloc] init];
carObject.make = @"Chevy";
//set other properties and create more objects
NSMutableArray *carList = [[NSMutableArray alloc] init];
[carList addObject:carObject]; //you can do this in a loop

显示时您可以使用[carList objectAtIndex:indexPath.row].make等。

或者

Car *myCar = [carList objectAtIndex:indexPath.row];
cell.textLabel.text = myCar.model;

When the user chooses some cars, save those model objects into a separate array and save it as plist.

于 2012-12-03T21:18:07.433 回答
2

Suppose, you added the following cars into an array as follows.

[arraySelectedCars addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"BMW", @"Makes", @"Mini", @"Model", @"chevy_volt.jpg", @"Image", nil]];
[arraySelectedCars addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"Toyota", @"Makes", @"Mini", @"Venza", @"toyota_venza.jpg", @"Image", nil]];

You can save them into NSUserDefaults, which reside into user's device till user delete apps or until you remove it.

[[NSUserDefaults standardUserDefaults] setValue:arraySelectedCars forKey:@"SelectedCars"];
[[NSUserDefaults standardUserDefaults] synchronize];

Later you can access the array and reload tableview as follows.

NSMutableArray *arraySelectedCars = [[NSUserDefaults standardUserDefaults] valueForKey:@"SelectedCars"];
于 2012-12-03T21:27:03.690 回答