Я пытаюсь получить некоторые данные, отображаемые в виде таблицы, которая является частью контроллера представления в контроллере панели. В настоящее время я запускаю приложение на iPhone Simulator. Я скопировал SQLite базу данных по следующему адресу - /Users/{имя пользователя}/Library Поддержка/Application/iPhoneSimulator/4,2/Применения/{APPID}/ДокументыОсновные данные: проблема с извлечением данных из базы данных sqlite
Теперь я пытаюсь извлечь данные в viewWillAppear
методе мой контроллер просмотра.
#import "FugitivesViewController.h"
#import "MyAppDelegate.h"
#import "Fugitive.h"
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSManagedObjectContext *context = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Fugitive" inManagedObjectContext:context];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[context executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
NSLog(@"Error while fetching the results");
}
self.items = mutableFetchResults;
[mutableFetchResults release];
[error release];
[request release];
[context release];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [self.items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
Fugitive *fugitive = [items objectAtIndex:indexPath.row];
cell.textLabel.text = fugitive.name;
return cell;
}
Проблема в том, что это ничего не обнаруживает в контроллере представления, никаких ошибок. Я подключил необходимые выходы в контроллере панели.
Проверка в отладчике измененного массива показывает 0 объектов. Я только начал разработку iOS. Может ли кто-нибудь помочь мне разобраться, что здесь может быть неправильным?
ОБНОВЛЕНИЕ - с помощью комментария Yuji я проверил файл, который копируется в папке «Документы» iPhone Simulator. У него нет никаких данных. Вот почему в представлении нет данных. Таким образом, проблема заключается в том, что код используется для копирования файла из папки проекта в папку документов приложения.
Вот как это происходит ....
// MyAppDelegate.m
#import "MyAppDelegate.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[self createEditableCopyOfDatabaseIfNeeded];
[self.window addSubview:tabcontroller.view];
[self.window makeKeyAndVisible];
return YES;
}
- (void)createEditableCopyOfDatabaseIfNeeded {
NSString *defaultDirectory = [[self applicationDocumentsDirectory] absoluteString];
NSString *writableDBPath = [defaultDirectory stringByAppendingPathComponent:@"iBountyHunder1.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:writableDBPath]) {
NSString *defaultDBPath = [[NSBundle mainBundle] pathForResource:@"iBountyHunder" ofType:@"sqlite"];
if (defaultDBPath) {
NSError *error;
BOOL success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSLog(@"The error is %@", [error localizedDescription]);
}
}
}
}
не удается получить, почему это не работает ????
Как вы создали базу данных sqlite? – Yuji
@Yuji - Я следую руководству Head First iPhone Development - скопировал базу данных sqlite здесь http://www.headfirstlabs.com/iphonedev - Глава 7 – vikmalhotra
Освобождение контекста управляемого приложения в viewWillAppear неверно. Указатель для объекта был восстановлен, но владение не было принято. – Evan