gpt4 book ai didi

iOS CoreData 无法使用 Objective-C 获取属性

转载 作者:行者123 更新时间:2023-11-30 12:34:35 27 4
gpt4 key购买 nike

我尝试使用objective-c编写核心数据。

我的快速代码可以获取如下所示的用户实体

swift 3:

 let appDel = UIApplication.shared.delegate as? AppDelegate;
guard let context = appDel?.persistentContainer.viewContext else{ return }
let User = User(context: context);

我使用objective-c在viewdidload中写入。

但我不能persistentContainer属性。

如下所示:

objective-c

  UIApplication *application = [UIApplication sharedApplication];

NSManagedObjectContext *context = (AppDelegate*)(application.delegate).
persistentContainer.viewContext;

有谁能解决无法获取permanentContainer属性的问题吗?

我使用的是Xcode8.2.1 Objective-C项目。

非常感谢。

最佳答案

*首先我们要在Appdelegate中导入核心数据框架,并设置perpeterContainer的属性在Appdelegate.h文件中

@property (readonly, strong) NSPersistentContainer *persistentContainer;

- (void)saveContext;

在Appdelegate.m文件中

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
// The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
@synchronized (self) {
if (_persistentContainer == nil) {
_persistentContainer = [[NSPersistentContainer alloc] initWithName:@"NSURL"];
[_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
if (error != nil) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
}
}];
}
}

return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
NSManagedObjectContext *context = self.persistentContainer.viewContext;
NSError *error = nil;
if ([context hasChanges] && ![context save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
}
}

关于iOS CoreData 无法使用 Objective-C 获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43029246/

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