我目前正在将Objective C应用程序更新到Swift 3.如何保存与从前一个表传递的对象关联的输入数据? Objective C应用程序运行正常,但我无法确定Swift 3的等效语法。
Objective C代码是:
- (void)insertNewObject:(NSString*) strRain;
{
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
Rainfall *altRainfall = (Rainfall*)[NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
altRainfall.gauge = strRain;
altRainfall.primaryGauge = self.detailItem;
altRainfall.dateRecorded = todaysDate;
altRainfall.sortDate = [NSDate date];
NSError *error = nil;
if (![context save:&error])
{
NSDictionary *dict = [error userInfo];
NSString *errMsg = [dict valueForKey:@"errMessage"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Note" message:errMsg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alert show];
[self.managedObjectContext deleteObject:altRainfall];
}}
Swift 3代码是:
func save(strRain: String) {
let entity = NSEntityDescription.entity(forEntityName: "Rainfall", in: coreDataStack.context)!
let newRainfall = NSManagedObject(entity: entity, insertInto: coreDataStack.context)
newRainfall.setValue(strRain, forKeyPath: "gauge")
newRainfall.setValue(todaysDate, forKeyPath: "dateRecorded")
newRainfall.setValue(sortDateItem, forKeyPath: "sortDate")
print(strRain)
print(todaysDate)
print(sortDateItem)
do {
try coreDataStack.context.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
那么,如何用Swift中的东西替换altRainfall.primaryGauge = self.detailItem?
答案 0 :(得分:0)
用于保存和更新数据。
func saveToDataBase(data:[TestData]){
for data1 in data{
let request:NSFetchRequest<TestData> = TestData.fetchRequest()
do {
let count = try managedObjectcontext.count(for: request)
if count == 0 {
// save data according to your requirement.
print(data1)
}else{
//if anything you want to update then wright here
}
}catch{
let error = error as NSError
print("\(error)")
}
}
}
您可以这样做以检索数据。
func retriveSaveData(){
let request:NSFetchRequest<TestData> = TestData.fetchRequest()
do {
let data = try managedObjectcontext.fetch(request) as [TestData]
if let str = data.first?.name{
// Your retrieve data
print(str)
}
}catch{
let error = error as NSError
print("\(error)")
}
}
希望它会对你有所帮助。如果你去看看coredata经理那么我已经做了样本项目。 project sample
答案 1 :(得分:0)
答案非常明显!我遗失的那条线是:
public void createPartControl(Composite parent) {
this.parent = parent;
createContent();
}
这会将数据与从上一个视图传递的量表名称相关联。很明显,我质疑为什么我还在努力学习。也许只是为了创造新的神经网络以避免衰老的发生。