简体   繁体   English

适用于目标C的可可Mac应用程序的SQLite教程概述

[英]Sqlite tutorial overview for my cocoa mac application in objective c

I am having a cocoa application for mac in objective c. 我在目标c中有针对Mac的可可应用程序。

Now, in my app I want to implement sqlite database like I did for ios apps. 现在,在我的应用程序中,我想像在ios应用程序中一样实现sqlite数据库。

As I am new to mac development, I am not sure how to implement this in cocoa application. 由于我是Mac开发的新手,所以我不确定如何在可可应用程序中实现此功能。 How to make sqlite connection to my app? 如何建立与我的应用的sqlite连接?

I used sqlite.h and sqlite.m files and used the below code. 我使用了sqlite.h和sqlite.m文件,并使用了以下代码。

-(void)databaseOpen
{
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [path objectAtIndex:0];
    NSString *myDBnew = [documentsDirectory stringByAppendingPathComponent:@"SchoolApp.sqlite"];
    database = [[Sqlite alloc] init];
    [database open:myDBnew];
}
- (void)createEditableCopyOfDatabaseIfNeeded
{
    // First, test for existence.
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];


    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"SchoolApp.sqlite"];


    /*if([[NSFileManager defaultManager] fileExistsAtPath:writableDBPath]){
     [[NSFileManager defaultManager] removeItemAtPath:writableDBPath error:nil];
     }
     */
    success = [fileManager fileExistsAtPath:writableDBPath];

    if (success) return;
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"SchoolApp.sqlite"];

    ////NSLog(@"Default : %@",defaultDBPath);
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];

    if (!success) {
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);

    }
}

but How to do this in my cocoa application? 但是如何在我的可可粉应用中做到这一点?

Please anyone can guide me. 请任何人都可以指导我。

Thanks... 谢谢...

You should be able to re-use your existing code for both OSX and iOS as this will rely on Foundation.framework classes, not UIKit or AppKit . 您应该能够在OSX和iOS上重用现有代码,因为这将依赖于Foundation.framework类,而不是UIKitAppKit

Note: you shouldn't be using NSAssert to signal errors in your code as these can be removed at compile time if NS_BLOCK_ASSERTIONS is defined; 注意:您不应该使用NSAssertNS_BLOCK_ASSERTIONS代码中的错误,因为如果定义了NS_BLOCK_ASSERTIONS则可以在编译时将其清除; instead throw an NSException . 而是抛出一个NSException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM