2013-12-05 2 views
-1

Я пытаюсь создать класс в Objective C, который содержит методы веб-службы и базы данных для моего приложения. В этом классе я хочу вызвать веб-службу и захватить записи сотрудников, а затем загрузить их в таблицу SQL для последующего использования в представлении.Доступ к свойствам и методам из одного класса внутри другого класса в Objective C

Я получил эту работу, когда весь код, как в представлении, но пытаясь сделать этот новый класс (то, что я называю GetEmployee), у меня возникают проблемы. Я не понимаю, как получить доступ к свойствам и методам из одного класса в другой.

Вот мой GetEmployee Класс

#import <Foundation/Foundation.h> 
#import "employee.h" 
#import "FMDatabase.h" 
#import "FMDatabaseAdditions.h" 
#import "FMDatabasePool.h" 
#import "FMDatabaseQueue.h" 
#import "FMResultSet.h" 
#import "Utility.h" 

@interface GetEmployee : NSObject 

{ 
    NSMutableArray *employees; 
} 

@property (nonatomic, copy) NSString *databaseName; 
@property (nonatomic, copy) NSString *databasePath; 

- (void)updateEmployeeData; 
- (void)callWebService; 
- (void)fetchedData:(NSData *)responseData; 

- (NSMutableArray *) getEmployees; 

@end 

реализация

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) 
#define scoularDirectoryURL [NSURL URLWithString: @"https://XXXXXXXXX/mobile/mobilede.nsf/restServices.xsp/PeopleByName"] 

#import "GetEmployee.h" 
#import "FMDatabase.h" 
#import "FMDatabaseAdditions.h" 
#import "FMResultSet.h" 

@implementation GetEmployee 


- (id) init 
{ 
    if (self = [super init]) 
    { 
     self.databaseName = @"employees.db"; 
    } 
    return self; 
} 

#pragma 

- (void)updateEmployeeData{ 

    //Delete database if it exists and then copy fresh DB 
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentDir = [documentPaths objectAtIndex:0]; 
    self.databasePath = [documentDir stringByAppendingPathComponent:self.databaseName]; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    BOOL success; 
    success = [fileManager fileExistsAtPath:self.databasePath]; 
    if (success) { 
     [fileManager removeItemAtPath:self.databasePath error:nil]; 
    } 
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseName]; 
    [fileManager copyItemAtPath:databasePathFromApp toPath:self.databasePath error:nil]; 

    //Call the web service 
    [self callWebService]; 
    [self populateDatabase]; 
} 

- (void) callWebService { 
    dispatch_sync(kBgQueue, ^{ 
     NSData* data = [NSData dataWithContentsOfURL: 
         scoularDirectoryURL]; 
     [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; 
    }); 
} 

- (void)fetchedData:(NSData *)responseData { 

    NSError* error; 
    NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &error]; 
    id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; 

    employees = [[NSMutableArray alloc] init]; 

    if (!jsonArray) { 

    } else { 

     for (jsonObject in jsonArray){ 
      employee *thisEmployee = [employee new]; 
      thisEmployee.fullName = [jsonObject objectForKey:@"$13"]; 
      thisEmployee.ste  = [jsonObject objectForKey:@"state"]; 
      thisEmployee.city  = [jsonObject objectForKey:@"city"]; 
      [employees addObject:thisEmployee]; 
     } 
    } 
} 



-(void) populateDatabase { 



////Call the web service and populate the db 
//dispatch_sync(kBgQueue, ^{ 
// NSData* data = [NSData dataWithContentsOfURL: 
//     scoularDirectoryURL]; 
// [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; 
//}); 

//Populate the db 
FMDatabase *db = [FMDatabase databaseWithPath:[Utility getDatabasePath]]; 
[db open]; 
for (employee *thisemployee in employees) { 
    BOOL success = [db executeUpdate:@"INSERT INTO employees (fullname,city,state) VALUES (?,?,?);",thisemployee.fullName,thisemployee.city,thisemployee.ste, nil]; 
    if (success) {} // Only to remove success error 
} 
[db close]; 

} 




- (NSMutableArray *) getEmployees 

{ 

    //NSMutableArray *employees = [[NSMutableArray alloc] init]; 
    employees = [[NSMutableArray alloc] init]; 
    FMDatabase *db = [FMDatabase databaseWithPath:[Utility getDatabasePath]]; 
    [db open]; 
    FMResultSet *results = [db executeQuery:@"SELECT * FROM employees"]; 

    while([results next]) 
    { 
     employee *thisEmployee = [employee new]; 
     thisEmployee.fullName = [results stringForColumn:@"fullname"]; 
     thisEmployee.city  = [results stringForColumn:@"city"]; 
     thisEmployee.ste  = [results stringForColumn:@"state"]; 
     [employees addObject:thisEmployee]; 
    } 

    [db close]; 

    return employees; 

} 

@end 

А вот MasterViewController

заголовка

#import <UIKit/UIKit.h> 
#import "employee.h" 
#import "FMDatabase.h" 
#import "FMResultSet.h" 
#import "FMDatabaseAdditions.h" 
#import "Utility.h" 

#import "GetEmployee.h" 

@interface MasterViewController : UITableViewController 
{ 
    NSMutableArray *employees; 
    //GetEmployee *ScoularEmployees; 
} 

@end 

реализация

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) 
#define scoularDirectoryURL [NSURL URLWithString: @"https://xxxxxxxx/mobile/mobilede.nsf/restServices.xsp/PeopleByName"] 

#import "MasterViewController.h" 
#import "DetailViewController.h" 
#import "employee.h" 
#import "GetEmployee.h" 

@interface MasterViewController() { 
    NSMutableArray *_objects; 
} 

@property(strong, nonatomic) GetEmployee *ScoularEmployees; 

@end 


@implementation MasterViewController 

- (void)awakeFromNib 
{ 
    [super awakeFromNib]; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    //GetEmployee *ScoularEmployees = [[GetEmployee alloc] init]; 
    [self.ScoularEmployees init]; 

    //[self.ScoularEmployees init]; 

    //_ScoularEmployees = [[GetEmployee alloc] init]; 
    //[_ScoularEmployees getEmployees]; 
    //GetEmployee *ScoularEmployees = [[GetEmployee alloc] init]; 
    //GetEmployee *thisEmployeeData = [[GetEmployee alloc] init]; 
    //[self.ScoularEmployees updateEmployeeData]; 
    //[self.ScoularEmployees getEmployees]; 
    //[ScoularEmployees updateEmployeeData]; 
    //[ScoularEmployees getEmployees]; 
} 


#pragma mark - Table View 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 

    return employees.count; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 
    NSString *fullName = [[employees objectAtIndex:indexPath.row] valueForKey:@"fullName"]; 
    cell.textLabel.text = fullName; 
    return cell; 
} 

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Return NO if you do not want the specified item to be editable. 
    return YES; 
} 

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     [_objects removeObjectAtIndex:indexPath.row]; 
     [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    } else if (editingStyle == UITableViewCellEditingStyleInsert) { 
     // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. 
    } 
} 

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    if ([[segue identifier] isEqualToString:@"showDetail"]) { 
     NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow]; 
     employee *dtlEmployee = [employees objectAtIndex:indexPath.row]; 
     [[segue destinationViewController] setDetailItem:dtlEmployee]; 
    } 
} 


- (void)fetchedData:(NSData *)responseData { 

    NSError* error; 
    NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &error]; 
    id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; 

    //employees = [[NSMutableArray alloc] init]; 

    if (!jsonArray) { 

    } else { 
     //NSMutableArray *employees = [[NSMutableArray alloc ]init]; 
     for (jsonObject in jsonArray){ 
      employee *thisEmployee = [employee new]; 
      thisEmployee.fullName = [jsonObject objectForKey:@"$13"]; 
      thisEmployee.ste  = [jsonObject objectForKey:@"state"]; 
      thisEmployee.city  = [jsonObject objectForKey:@"city"]; 
      [employees addObject:thisEmployee]; 
     } 
    } 

    } 


//-(NSMutableArray *) getEmployees 

//{ 

    //NSMutableArray *employees = [[NSMutableArray alloc] init]; 
    //employees = [[NSMutableArray alloc] init]; 
// FMDatabase *db = [FMDatabase databaseWithPath:[Utility getDatabasePath]]; 
// [db open]; 
// FMResultSet *results = [db executeQuery:@"SELECT * FROM employees"]; 
// 
// while([results next]) 
// { 
//  employee *thisEmployee = [employee new]; 
//  thisEmployee.fullName = [results stringForColumn:@"fullname"]; 
//  thisEmployee.city  = [results stringForColumn:@"city"]; 
//  thisEmployee.ste  = [results stringForColumn:@"state"]; 
//  //[employees addObject:thisEmployee]; 
// } 
// 
// [db close]; 
// 
// return employees; 
    // return true; 
//} 



@end 

Любая помощь была бы принята с благодарностью.

Я думал, что это было ясно, но я вижу, что это не так. В классе вида я хочу иметь возможность загружать NSMutableArray, называемые * сотрудниками, которые поступают из базы данных SQLLite и выходят из них на экране. Я попытался централизовать код доступа к данным в классе GetEmployee. Все в этом классе имеет дело с данными - веб-службой, загрузкой данных в базу данных и получением данных из базы данных. Поэтому в этом классе у меня есть метод «getEmployees», который получает данные из db и загружает его в этот NSMutableArry. Итак, вот в чем проблема: в классе я не могу получить доступ к методам или свойствам в GetEmpployee. Это мой вопрос.

+2

, что ваш вопрос и то, что этот код здесь делает? –

+0

Не просто бросьте огромную кучу кода у нас, не говоря о том, в чем проблема. Уточните свой вопрос и и сузите код только к соответствующим частям. – rmaddy

+0

Я думал, что это ясно, но я вижу, что это не так. –

ответ

0

Без чтения через весь код вы публикуемую ...

Для использования метода класса, синтаксис:

[ClassName methodName]; 
[ClassName anotherMethod:withArguments]; 

методы, которые вызываются с помощью этого синтаксис будет выглядеть в соответствующий файл .h:

+(void)methodName; 
+(void)anotherMethod:(NSNumber*)number; 

Для использования метод экземпляра, синтаксис:

ClassName myObj = [[ClassName alloc] init]; 
[myObj someMethod]; 
[myObj someOtherMethod:withArguments]; 

метода, которые вызываются с помощью этого синтаксиса будет выглядеть в соответствующем файле .h:

-(void)someMethod; 
-(void)someOtherMethod:(NSString*)parameter; 
Смежные вопросы