我有一個由標題和圖像條目填充的表格。這可以通過以下方法進行:我可以使用NSUserDefaults來保存應用程序的表格單元格值嗎?
tablePhotoViewController.m
- (IBAction)takePicture:(UIBarButtonItem *)sender {
// check #1 - make sure our source type is supported
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
// check #2 see if media type includes images
if ([mediaTypes containsObject:(NSString *)kUTTypeImage]) {
// create our image picker
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeImage];
picker.allowsEditing = YES;
[self presentViewController:picker animated:YES completion:nil];
}
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// do something with this image
UIImage *imagefromcamerabutton = [info objectForKey:UIImagePickerControllerEditedImage];
// handle the case where editting was not allowed...
if (!imagefromcamerabutton) imagefromcamerabutton = [info objectForKey:UIImagePickerControllerOriginalImage];
// save to photo albumn
ALAssetsLibrary *al = [Utils defaultAssetsLibrary];
[al writeImageToSavedPhotosAlbum:[imagefromcamerabutton CGImage] metadata:nil
completionBlock:^(NSURL *assetURL, NSError *error)
{
// once we know it's saved, grab the ALAsset and store
// it in our collection for display later
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
[self.photos addObject:myasset];
[self.tableView reloadData];
};
ALAssetsLibrary *assetslibrary = [Utils defaultAssetsLibrary];
[assetslibrary assetForURL:assetURL
resultBlock:resultblock
failureBlock:nil];
}];
[self dismissImagePicker];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.photos count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
ALAsset *asset = [self.photos objectAtIndex:indexPath.row];
[cell.imageView setImage:[UIImage imageWithCGImage:[asset thumbnail]]];
[cell.textLabel setText:[NSString stringWithFormat:@"Thing %d", indexPath.row+1]];
return cell;
}
這個效果很好,但問題是,用戶關閉應用程序後,該單元的數據被擦除。我希望這些能夠保持照片不斷與表格相關聯,除非用戶點擊按鈕將其從陣列中刪除。從我對這項工作的理解有限,看起來我需要以某種方式實施NSUserDefaults
是對的還是有更好的做法來實現這一目標?
NSUserDefaults只能用於保存少量數據,比如幾個字符串或數字。使用文件存儲實際數據。 – rmaddy
@rmaddy你有沒有參考資料,我可以在這裏瞭解更多關於使用文件存儲數據的信息? – Presto