从Objective C中的另一个类中的一个类访问属性和方法

时间:2013-12-05 20:42:55

标签: objective-c

我正在尝试在Objective C中构建一个包含为我的应用程序提供Web服务和数据库方法的类。在这个类中,我想调用Web服务并获取员工记录,然后将它们加载到SQL表中,以便以后在视图中使用。

当所有代码都在视图中时,我得到了这个工作,但在尝试创建这个新类(我称之为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

非常感谢任何帮助。

我认为很清楚,但我可以看到它不是。在视图类中,我希望能够加载一个名为* employees的NSMutableArray,它来自SQLLite数据库并在屏幕上显示出来。我试图在GetEmployee类中集中数据访问的代码。该类中的所有内容都处理数据 - Web服务,将数据加载到数据库,以及从数据库中获取数据。因此,在该类中,我有一个方法“getEmployees”,它从数据库获取数据并将其加载到NSMutableArry中。所以这就是问题,在类中我无法访问GetEmpployee中的方法或属性。这是我的问题。

1 个答案:

答案 0 :(得分:0)

无需阅读您发布的所有代码......

对于使用Class方法,语法为:

[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;
相关问题