gpt4 book ai didi

swift - 将数据保存在 Swift 的 Core Data 中

转载 作者:行者123 更新时间:2023-11-30 12:49:08 25 4
gpt4 key购买 nike

我目前正在将 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 呢?

最佳答案

用于保存和更新数据。

 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 manager 那么我已经制作了示例项目。 project sample

关于swift - 将数据保存在 Swift 的 Core Data 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41233285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com