[英]How to call appdelegete method in different class in iphone
我有一个包含 10 个表的数据库。 由于我需要在不同的视图控制器中访问这个数据库,我必须在每个视图控制器中声明如下所示的两种方法。 有没有办法通过在应用程序委托中声明这些方法来避免这种情况。 如果是,我该如何在不同的类中使用这些方法。
- (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]);
}
}
在您看来 controller 首先创建一个委托变量
YourAppDelegate *appDelegate=(YourAppDelegate *)[[UIApplication sharedApplication]delegate];
然后您可以调用您在委托中定义的任何方法,例如[appDelegate methodName];
这只是尖叫着要实现为具有 class 级别方法的单独 controller 。 我强烈建议创建一个数据库 controller,其定义如下:
@interface DatabaseController: NSObject
+ (NSString *) getWritableDBPath ;
+ (void) createEditableCopyOfDatabaseIfNeeded ;
@end
然后在您的代码中使用它:
#import "DatabaseController.h"
NSString * somePath = [DatabaseController getWritableDBPath];
[DatabaseController createEditableCopyOfDatabaseIfNeeded];
将它们设置为公开,以便您可以使用 [ ] 调用它们
您只需将减号更改为 +
+(void)createEditableCopyOfDatabaseIfNeeded;
首先为appdelegate
创建一个公共实例。 否则在constant.h
文件中创建一个实例
mAppDelegate=(YourAppDelegate*)[[UIApplication sharedApplication] ];
然后只需导入constant.h ,您就可以在任何地方使用mAppdelegate
,因此您可以轻松调用它
您需要为此 class 定义一个协议,并将该协议的变量添加到此 class 的成员变量中,如下所示:
创建 object 的类可以使用 object 调用此方法。 最佳选择是使用应用程序委托 class 来实现这些方法。
然后,您可以将对象的委托分配为应用委托并调用方法。
@protocol mySqlDelegate ;
@interface mySqlClass {
id <mySqlDelegate> delegate;
}
@property (nonatomic, assign) id <mySqlDelegate> delegate;
@end
@protocol mySqlDelegate
- (void) delegateMethodsForThisClass;
@end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.