点击此教程:http://mobile.tutsplus.com/tutorials/iphone/iphone-core-data/
我在AppNameDelegate.m文件中使用fetch records方法。然后我在我的tableview上调用reload。与链接教程不同,我没有使用UITableViewController。相反,我已经向NavigationController添加了一个表视图,并将其连接到名为contactsTable的IBOutlet变量。
这是我调用和加载数据的代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self.window addSubview:[self.navigationController view]];
[self fetchRecords];
[self.contactsTable reloadData];
[self.window makeKeyAndVisible];
}
标题文件:
//
// SimpleContactsAppDelegate.h
// SimpleContacts
//
// Created by Aaron McLeod on 11-05-28.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
@interface SimpleContactsAppDelegate : NSObject <UIApplicationDelegate> {
NSManagedObjectModel *managedObjectModel;
NSManagedObjectContext *managedObjectContext;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
UIWindow *window;
UINavigationController *navigationController;
// view for adding new contacts
UIViewController *newContactView;
UIButton *addButton;
// controls for the addContactView
UIButton *saveContactButton;
UITextField *nameField;
UITextField *emailField;
UITextField *phoneField;
UITableView *contactsTable;
NSMutableArray *contactArray;
}
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
@property (nonatomic, retain) IBOutlet UIButton *addButton;
@property (nonatomic, retain) IBOutlet UITableView *contactsTable;
@property (nonatomic, retain) NSMutableArray *contactArray;
// controller and fields for the form
@property (nonatomic, retain) IBOutlet UIViewController *newContactView;
@property (nonatomic, retain) IBOutlet UITextField *nameField;
@property (nonatomic, retain) IBOutlet UITextField *emailField;
@property (nonatomic, retain) IBOutlet UITextField *phoneField;
@property (nonatomic, retain) IBOutlet UIButton *saveContactButton;
- (NSString *)applicationDocumentsDirectory;
- (IBAction) saveContact;
- (IBAction) switchToAddContactView;
- (void)fetchRecords;
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView;
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
@end
您也可以在此处找到我的项目源代码:https://github.com/agmcleod/SimpleContacts/tree/parttwo如果我遗漏了您可能需要的代码。感谢。
答案 0 :(得分:0)
reloadData
唯一能做的就是告诉UITableView
向其数据源询问新数据。这意味着它会调用numberOfSectionsInTableView:
等。您是否正确设置了这种关系?
在您的情况下,您的SimpleContactsAppDelegate
实例应该是表视图的dataSource
(在Interface Builder中进行连接)。
在使用Core Data和UITableViews时,请考虑使用NSFetchedResultsController
。这允许您不会立即将所有对象加载到内存中等.Xcode的示例代码为此提供了一个很好的起点(我认为它是基于导航控制器的应用程序,带有Core Data模板)。