如何从xcode 6中的核心数据中获取数据

时间:2015-02-19 12:27:41

标签: xcode6

我是iOS开发新手,我正在使用XCode 6.

我正在研究coredata,我已经在coredata上完成了保存,删除和更新数据,但现在我无法从coreData搜索现有数据。所以,任何人都可以告诉我该怎么办?

1 个答案:

答案 0 :(得分:0)

  

ViewController.h

import

@interface SecondViewController :       UIViewController<UITableViewDataSource,UITableViewDelegate>
{
   IBOutlet UITableView *tableview;
 }
 @property (strong) NSMutableArray *devices;
- (IBAction)goBack:(id)sender;
@end
  

ViewController.m

#import "SecondViewController.h"
#import <CoreData/CoreData.h>
@interface SecondViewController ()
{
   NSManagedObjectContext *context ;
}
@end

@implementation SecondViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}



- (NSManagedObjectContext *)managedObjectContext
{
context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
    context = [delegate managedObjectContext];
}
return context;
}


- (void)viewDidAppear:(BOOL)animated
   {
    [super viewDidAppear:animated];

// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Device"];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

[tableview reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}

   - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:   (NSInteger)section
  {
  // Return the number of rows in the section.
  return self.devices.count;
   }

   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
   { 
static NSString *CellIdentifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

// Configure the cell...
NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:@"%@ ", [device valueForKey:@"name1"]]];

return cell;
}