DB Wrapper Not Responding to Message?

DB Wrapper Not Responding to Message?

居里长安 发布于 2021-11-28 字数 2328 浏览 770 回复 1 原文

I'm developing for iphone-sdk 2.2.1 (so no CoreData cry).

So I'm using the FMDatabase project, which is just a SQLite Wrapper in Obj C. I have my DB working well when interacting with it from my AppDelegate. I've tested connecting, INSERTING, etc from the AppDelegate.

Now, I have a data object that I want to store into the Database. I would like this event to occur from a ViewController class. Lets see some code:

App Delegate Creates the DB in the applicationDidFinishLaunching method. The DB is declared as a property of this class so I can easily access it.

db = [FMDatabase databaseWithPath:[self getDBPath]];

This works fine, I have tested it. The only thing I'm a little concerned about is 'db' being a property of the class. That shouldn't cause problems, should it?

From the same applicationDidFinishLaunching method, I've tested that a simple insert works using. This Works:

[db beginTransaction];
[db executeUpdate:@"INSERT INTO tblDataSamples (...) VALUES (...);"];
[db commit];

Now, if I simply take this exact code and move it to an instance method of the AppDelegate, the code no longer works. I get a "EXC_BAD_ACCESS" error when we hit the [db beginTransaction] line.

The flow of this code to this call:
- AltViewController Receives a button tap Event
- AltViewController tells ApplicationDelegate to execute the "addSample" method.
- ApplicationDelegate's addSample method fails on [db beginTransaction].

Now that I've written this out, I am thinking the problem is that my DB gets lost after the ApplicationDelegate loads the RootView. Maybe I'm wrong though. Anyone have any ideas?


I just altered my addSample method to include

db = [FMDatabase databaseWithPath:[self getDBPath]];
    if (![db open]) {
        NSLog(@"Could not open db.");


[db close];

The entire transaction works now. So, the new question is: how do I make the database open ONCE and stay open across different views and viewControllers?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。



需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。


鸢与 2022-06-07 1 楼

You're having trouble because you don't know the memory management rules yet. In this case, the databaseWithPath: method returns an autoreleased object, which is disposed of at the end of the run loop. Your db pointer still points to that invalid memory location though, which is why you're seeing the EXC_BAD_ACCESS error when you try to access it later on.

The good news is that memory management is actually pretty easy to learn in Cocoa. Have a look at this page for starters, it should have enough information to get you going. To solve this particular problem you would need to call the retain method on your db object after it's created, and release it when it's no longer needed (if you're keeping it for the life of your application there's nothing gained by releasing it, but it's still good practice).