【发布时间】:2014-02-21 02:29:54
【问题描述】:
我是 ios 编程新手,我正在创建这个简单的功能,让视图控制器将数据添加到持久存储中,然后表视图控制器将获取这些数据并按行显示它们。
我要添加的这个数据是一个来自 UITextField 的字符串,我已将 IBAction 连接到“添加”按钮,该按钮为 UITextField 获取文本并将其添加。
重新启动 iOS 模拟器后,我能够观察到新数据被添加。但是,我无法即时看到更改(在同一测试运行中)。
我能否知道我是否应该每次都关闭并重新打开 iOS 模拟器(这不是我希望为我的用户提供的用户体验),还有什么可以解决的吗?
谢谢!
这是我的 ViewController 中的 IBAction 代码:
- (IBAction)addFriendEntry:(id)sender {
NSManagedObjectContext *moc = [self managedObjectContext];
NSManagedObject *newFriend = [NSEntityDescription
insertNewObjectForEntityForName:@"Player"
inManagedObjectContext:moc];
[newFriend setValue:self.friendNameTextField.text forKey:@"name"];
NSLog(@"You are trying to add this friend:%@", self.friendNameTextField.text);
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(@"Oops, couldn't save: %@", [error localizedDescription]);
}
self.friendNameTextField.text = @"";
[self.view endEditing:YES];
}
这是我在 TableViewController 中的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
self.Friends = [[NSMutableArray alloc] init];
PCRAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
self.Friends = [appDelegate fetchFriendsFromDataBase];
//Some small test to tell me that the app is responding to me everytime I switch to the TableViewController
NSLog(@"hi from tableview");
[self.tableView reloadData];
}
我的 AppDelegate.h 中有一些其他方法,其中包括:
- (NSManagedObjectContext *)managedObjectContext;
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator;
- (NSManagedObjectModel *)managedObjectModel;
- (NSArray *)fetchFriendsFromDataBase;
我的 fetchFriendsFromDataBase 方法是:
- (NSArray *)fetchFriendsFromDataBase
{
//Takes in name of friend. Using this name, which is an attribute, find the entity from persistent store and pull out the NSManagedObject.
//initializing NSFetchRequest
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//Sets Entity to be queried
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Player" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
//Execute Fetch Request
NSArray *fetchedPlayers = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
return fetchedPlayers;
}
当我单击添加触发 IBAction 时,我仍然看不到任何更改。
【问题讨论】:
-
你能分享一些你的代码吗?
-
您需要提供有关您的代码实际执行的更多详细信息。您是否将 fetchedResultsController 与 UITableView 一起使用,如果没有,那么您如何将 UITableView 连接到数据源?你是如何在persistentStore 中创建对象的?最重要的是,您应该在进行更改后立即看到 tableView 中的任何更改。
-
我主要遵循本教程并从中获取了大部分代码:codigator.com/tutorials/ios-core-data-tutorial-with-example 我的 AppDelegate 中有 -fetchAllNames,就像我的 viewcontroller.m 中的教程和 IBAction addEntry 一样
标签: ios iphone objective-c core-data on-the-fly