核心数据在获取请求中再次插入重复值

时间:2015-10-22 12:00:48

标签: ios iphone core-data

我正在学习核心数据,所以在核心数据上做一个例子时,我已经陷入了以下问题:

每当我调用Fetch请求时,都会插入一个新数据。有人可以帮助我吗?

- (IBAction)save:(id)sender
{

    NSString *svd = self.text1.text;
    AppDelegate * appdel = (AppDelegate *)[[UIApplication sharedApplication]delegate];


        NSEntityDescription * entity = [NSEntityDescription insertNewObjectForEntityForName:@"Students" inManagedObjectContext: appdel.managedObjectContext];



    [entity setValue:svd forKey:@"name"];
    NSError *error;
   BOOL isSaved= [appdel.managedObjectContext save:&error];

    NSLog(@"Sucessfully Saved %d",isSaved);

}

- (IBAction)fetch:(id)sender
{

    AppDelegate * appdel = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    NSEntityDescription * entity = [NSEntityDescription entityForName:@"Students" inManagedObjectContext:appdel.managedObjectContext];


    //Create a Fetch Request.
    NSFetchRequest *fetch = [[NSFetchRequest alloc]init];
    [fetch setEntity:entity];

    //Save all fetched rows in mutable array.

    arr =[[appdel.managedObjectContext executeFetchRequest:fetch error:nil]mutableCopy];

    //coredata returns each row as managed object so we save that in array
    for (NSManagedObject *obj in arr )
    {
//        NSString *ans = [obj valueForKey:@"name"];
//  
//        [savedata addObject:ans];

        NSLog(@"Names : %@",[obj valueForKey:@"name"]);


    }

//     [tableview reloadData];

}

0 个答案:

没有答案