如何从类中创建NSString函数然后调用它?

时间:2014-04-13 07:29:30

标签: objective-c database class

我创建了一个子类NSObject"数据库"它创建了Database.h和Database.m,我想要做的是创建一个调用数据库的类。

我创建了这样的代码

#import "Database.h"

@implementation Database
NSString* docsDir;
NSArray* dirPaths;
NSString* dbsePath;

NSString *getDB()
{
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = dirPaths[0];
    // Build the path to the database file
    dbsePath = [[NSString alloc]
                initWithString: [docsDir stringByAppendingPathComponent:
                                 @"DBUntilAgo.sqlite"]];
    NSLog(@"1!%@",dbsePath);
    return dbsePath;
}


@end

这是对的吗?以及如何拨打电话到另一个视图?请帮助。我是Xcode的新手。

1 个答案:

答案 0 :(得分:0)

这应该是您的Database.h文件

@interface Database: NSObject
{

}

-(NSString *)getDB;
@end

这应该是您的Database.m文件

#import "Database.h"

@implementation Database

-(NSString *)getDB {
    NSString* docsDir;
    NSArray* dirPaths;
    NSString* dbsePath;

    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = dirPaths[0];
    // Build the path to the database file
    dbsePath = [[NSString alloc]
                initWithString: [docsDir stringByAppendingPathComponent:
                                 @"DBUntilAgo.sqlite"]];
    NSLog(@"1!%@",dbsePath);
    return dbsePath; } 
@end

然后让我们从AppDelegate.m说你可以创建这样的东西

#import "AppDelegate.h"
#import "Database.h"

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Override point for customization after application launch.

    Database *db=[[Database alloc] init];
    NSLog(@"%@",[db getDB]);




    //    RootNavigationController *root=[[RootNavigationController alloc] initWithRootViewController:[RootNavigationController RootViewControllerCandidate]];
    //    [root setNavigationBarHidden:YES];

    //    [self.window setRootViewController:root];

    [self.window makeKeyAndVisible];

    return YES;
}

@end