ios 清除完整的领域数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26067193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Clear complete Realm Database
提问by floriankrueger
I'm playing around with realm (currently 0.85.0) and my application uses the database to store user-specific data such as the contacts of the current user. When the user decides to log out I need to remove every single bit of information about the user and the most obvious, simple and clean thing in my opinion would be to wipe the complete realm. Unfortunately, the Cocoa lib doesn't provide that functionality.
我正在使用领域(当前为 0.85.0),我的应用程序使用数据库来存储特定于用户的数据,例如当前用户的联系人。当用户决定注销时,我需要删除关于用户的每一点信息,在我看来,最明显、最简单和干净的事情是擦除整个领域。不幸的是,Cocoa 库不提供该功能。
Currently, I'm stuck with the following
目前,我坚持以下
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
[realm deleteObjects:[MyRealmClass1 allObjectsInRealm:realm]];
[realm deleteObjects:[MyRealmClass2 allObjectsInRealm:realm]];
[realm deleteObjects:[MyRealmClass3 allObjectsInRealm:realm]];
[realm commitWriteTransaction];
any better ideas?
有什么更好的想法吗?
thanks
谢谢
回答by DonVaughn
Update:
更新:
Since posting, a new method has been added to delete all objects (as jpsim has already mentioned):
自发布以来,添加了一个新方法来删除所有对象(正如 jpsim 已经提到的):
// Obj-C
[realm beginWriteTransaction];
[realm deleteAllObjects];
[realm commitWriteTransaction];
// Swift
try! realm.write {
realm.deleteAll()
}
Note that these methods will not alter the data structure; they only delete the existing records. If you are looking to alter the realm model properties without writing a migration (i.e., as you might do in development) the old solution below may still be useful.
请注意,这些方法不会改变数据结构;他们只删除现有记录。如果您希望在不编写迁移的情况下更改领域模型属性(即,就像您在开发中所做的那样),下面的旧解决方案可能仍然有用。
Original Answer:
原答案:
You could simply delete the realm file itself, as they do in their sample code for storing a REST response:
您可以简单地删除领域文件本身,就像他们在用于存储 REST 响应的示例代码中所做的那样:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//...
// Ensure we start with an empty database
[[NSFileManager defaultManager] removeItemAtPath:[RLMRealm defaultRealmPath] error:nil];
//...
}
Update regarding your comment:
关于您的评论的更新:
If you need to be sure that the realm database is no longer in use, you could put realm's notifications to use. If you were to increment an openWrites
counter before each write, then you could run a block when each write completes:
如果您需要确保不再使用领域数据库,您可以使用领域的通知。如果您要openWrites
在每次写入之前增加一个计数器,那么您可以在每次写入完成时运行一个块:
self.notificationToken = [realm addNotificationBlock:^(NSString *notification, RLMRealm * realm) {
if([notification isEqualToString:RLMRealmDidChangeNotification]) {
self.openWrites = self.openWrites - 1;
if(!self.openWrites && self.isUserLoggedOut) {
[[NSFileManager defaultManager] removeItemAtPath:[RLMRealm defaultRealmPath] error:nil];
}
}
}];
回答by jonchoi
RealmSwift: Simple reset using a flag
RealmSwift:使用标志简单重置
Tried the above answers, but posting one more simple way to delete the realm file instead of migrating:
尝试了上述答案,但发布了一种更简单的方法来删除领域文件而不是迁移:
Realm.Configuration.defaultConfiguration.deleteRealmIfMigrationNeeded = true
This simply sets a flag so that Realm can delete the existing file rather than crash on try! Realm()
这只是设置一个标志,以便 Realm 可以删除现有文件而不是崩溃 try! Realm()
Instead of manually deleting the file
而不是手动删除文件
Thought that was simpler than the Swift version of the answer above:
认为这比上面答案的 Swift 版本更简单:
guard let path = Realm.Configuration.defaultConfiguration.fileURL?.absoluteString else {
fatalError("no realm path")
}
do {
try NSFileManager().removeItemAtPath(path)
} catch {
fatalError("couldn't remove at path")
}
回答by jpsim
As of realm 0.87.0, it's now possible to delete all realm contents by calling [[RLMRealm defaultRealm] deleteAllObjects]
from a write transaction.
从领域0.87.0 开始,现在可以通过[[RLMRealm defaultRealm] deleteAllObjects]
从写入事务中调用来删除所有领域内容。
From Swift, it looks like this: RLMRealm.defaultRealm().deleteAllObjects()
从 Swift 来看,它看起来像这样: RLMRealm.defaultRealm().deleteAllObjects()
回答by Glen Selle
In case someone stumbles on this question looking for a way to do this in Swift, this is just
DonamiteIsTnt's answer rewritten. I've added this function to a custom utility class so I can do MyAppUtilities.purgeRealm()
during testing & debugging
万一有人偶然发现这个问题,寻找在 Swift 中执行此操作的方法,这只是重写了 DonamiteIsTnt 的答案。我已将此函数添加到自定义实用程序类中,以便MyAppUtilities.purgeRealm()
在测试和调试期间执行
func purgeRealm() {
NSFileManager.defaultManager().removeItemAtPath(RLMRealm.defaultRealmPath(), error: nil)
}
Note:If you find yourself in need of clearing data you might just check out Realm's new realm.addOrUpdateObject()
feature which allows you to replace existing data by its primary key with the new data. This way you're not continually adding new data. Just replacing "old" data. If you do use addOrUpdateObject()
make sure you override your model's primaryKey
class function so Realm knows which property is your primary key. In Swift, for example:
注意:如果您发现自己需要清除数据,您可以查看 Realm 的新realm.addOrUpdateObject()
功能,该功能允许您将现有数据的主键替换为新数据。这样您就不会不断添加新数据。只是替换“旧”数据。如果您确实使用,请addOrUpdateObject()
确保您覆盖了模型的primaryKey
类函数,以便 Realm 知道哪个属性是您的主键。在 Swift 中,例如:
override class func primaryKey() -> String {
return "_id"
}
回答by Steve Pascoe
I ran into this fun little issue. So instead i queried the schema version directly before running the schemamigration.
我遇到了这个有趣的小问题。因此,我在运行架构迁移之前直接查询架构版本。
NSError *error = NULL;
NSUInteger currentSchemaVersion = [RLMRealm schemaVersionAtPath:[RLMRealm defaultRealmPath] error:&error];
if (currentSchemaVersion == RLMNotVersioned) {
// new db, skip
} else if (currentSchemaVersion < 26) {
// kill local db
[[NSFileManager defaultManager] removeItemAtPath:[RLMRealm defaultRealmPath] error:&error];
if (error) {
MRLogError(error);
}
} else if (error) {
// for good measure...
MRLogError(error);
}
// perform realm migration
[RLMRealm setSchemaVersion:26
forRealmAtPath:[RLMRealm defaultRealmPath]
withMigrationBlock:^(RLMMigration *migration, NSUInteger oldSchemaVersion) {
}];
回答by Prathma Rastogi
You can also go to the location where your realm file is stored, delete that file from there and next time when you open realm after running app, you will see the empty realm database in browser.
您也可以转到存储您的领域文件的位置,从那里删除该文件,下次运行应用程序后打开领域时,您将在浏览器中看到空领域数据库。