随机创建点击对象

//右按钮点击事件
- (void)barButtonItemClicked{
    //创建数据
    int randomName = arc4random() %300 +160000;
    NSArray *cityArray = @[@"上海",@"天津",@"北京",@"郑州",@"广州"];
    int randomCity = arc4random() %5;
    NSString *cityStr = [cityArray objectAtIndex:randomCity];
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *time = [formatter stringFromDate:date];
    
    //创建实体
    Classes *classes = [NSEntityDescription insertNewObjectForEntityForName:@"Classes" inManagedObjectContext:self.managedContext];
    //属性
    classes.classessName = [NSString stringWithFormat:@"BJS%d",randomName];
    classes.classessCity = cityStr;
    classes.classessTime = time;
    classes.classessImage = @"12.jpg";
    [_managedContext save:nil];
    
    [self.dataArray addObject:classes];
    [self.tableView reloadData];
    
}

删除对象
#pragma mark - 设置所有cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
#pragma mark -编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}
#pragma mark - 完成并提交
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        Classes *model = self.dataArray[indexPath.row];
        [self.managedContext deleteObject:model];
        NSError *error = nil;
        [self.managedContext save:&error];
        if (error == nil) {
            [self.dataArray removeObject:model];
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
        
    }
}

  






 

posted @ 2016-05-15 16:45  维他命11  阅读(237)  评论(0编辑  收藏  举报