Я пытаюсь отобразить некоторые данные в табличном представлении, которое является частью контроллера представления в контроллере вкладок. В настоящее время я пытаюсь запустить приложение на iPhone Simulator. Я скопировал базу данных sqlite в следующую папку -
/ Пользователи / {имя пользователя} / Библиотека / Поддержка приложений / iPhoneSimulator / 4.2 / Приложения / {appid} / Документы
Теперь я пытаюсь получить данные методом 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]);
}
}
}
}
Не могу понять, почему это не работает ????