2011-06-28 19 views
0

我有一個包含10個表的數據庫。因爲我需要在不同的視圖控制器中訪問這個數據庫,所以我必須在每個視圖控制器中聲明下面顯示的兩個方法。有沒有一種方法可以通過在應用程序委託中聲明這些方法來避免這種情況。如果是的話,我怎麼能在不同的課程中使用這些方法。如何在不同的類中調用appdelegete方法iphone

- (NSString *) getWritableDBPath { 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
    NSString *documentsDir = [paths objectAtIndex:0]; 
    return [documentsDir stringByAppendingPathComponent:DATABASE_NAME]; 
} 

-(void)createEditableCopyOfDatabaseIfNeeded 
{ 
    // Testing 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:DATABASE_NAME]; 
    NSLog(@"%@",writableDBPath); 

    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:DATABASE_NAME]; 
    success = [fileManager copyItemAtPath:defaultDBPath 
            toPath:writableDBPath 
            error:&error]; 
    if(!success) 
    { 
     NSAssert1(0,@"Failed to create writable database file with Message : '%@'.", 
        [error localizedDescription]); 
    } 
} 

回答

3

負在您的視圖控制器的所有創建一個委託變量

YourAppDelegate *appDelegate=(YourAppDelegate *)[[UIApplication sharedApplication]delegate]; 

然後你可以調用你在代理中定義的任何方法 like [appDelegate methodName];

+0

然後我想cretae我會強烈建議,象這樣的定義創建數據庫控制器像這樣[appdelegate getWritableDBPath]; [appdelegate createEditableCopyOfDatabaseIfNeeded]; – Rocky

+0

是什麼意思?沒有得到你 – Maulik

+0

是的maulik因爲我試試這爲什麼我說你 – Rocky

0

它們設置爲公開,這樣你就可以用[]稱呼他們

你只需要先更改+

+(void)createEditableCopyOfDatabaseIfNeeded; 
+0

什麼平均ü可以告訴我詳細 – Rocky

0

首先爲appdelegate創建一個通用實例。 否則constant.h文件中創建一個實例一樣

mAppDelegate=(YourAppDelegate*)[[UIApplication sharedApplication] ]; 

則只需導入constant.h,你可以使用mAppdelegate任何地方,所以用這個你輕鬆調用

0

您需要定義一個協議該類並將該協議的變量添加到此類的成員變量中,如下所示:

創建對象的類可以使用該對象調用此方法。最佳選擇是使用應用程序委託類來實現這些方法。

然後,您可以將對象的委託分配爲應用程序委託並調用方法。

@protocol mySqlDelegate ; 

@interface mySqlClass { 

    id <mySqlDelegate> delegate; 
} 
@property (nonatomic, assign) id <mySqlDelegate> delegate; 
@end 



@protocol mySqlDelegate 

- (void) delegateMethodsForThisClass; 

@end 
1

這只是尖叫作爲一個單獨的控制器與類級別的方法實施。使用它作爲這樣

@interface DatabaseController: NSObject 
    + (NSString *) getWritableDBPath ; 
    + (void) createEditableCopyOfDatabaseIfNeeded ; 
@end 

然後在你的代碼:

#import "DatabaseController.h" 


NSString * somePath = [DatabaseController getWritableDBPath]; 

[DatabaseController createEditableCopyOfDatabaseIfNeeded]; 
+0

這是穩定和乾淨的方式。 – kevboh

相關問題