2013-05-01 57 views
0

我對Objective-C非常陌生,這是我第一次嘗試實現MVC。我有一個模型類,其中l有一個NSArray,它將填充來自JSON對象的數據。我想填充我的UITableView(在我的視圖控制器類),從這個數組中的對象。獲取UITableView來填充來自另一個類的數據

請檢閱我的代碼:

Droplets.h

@interface Droplets : NSObject { 
    NSArray *dropletsArray; 

} 

// Get droplets data 
- (void) getDropletsList; 

//Object initilization 
- (id) init; 

//Public properties 
@property (strong, nonatomic) NSArray *dropletsArray; // Used to store the selected JSON data objects 

@end 

Droplets.m

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) 
#define kDigialOceanApiURL [NSURL URLWithString:@"http://inspiredwd.com/api-test.php"] //Droplets API call 

#import "Droplets.h" 

@interface Droplets() 

//Private Properties 
@property (strong, nonatomic) NSMutableData *data; // Used to store all JSON data objects 
@end 


@implementation Droplets; 

@synthesize dropletsArray; 
@synthesize data; 

- (id)init 
{ 
    self = [super init]; 
    if (self) { 

    } 
    return self; 
} 

- (void) getDropletsList { 

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 

    NSURL *url = kDigialOceanApiURL; // Predefined Digital Ocean URL API http request 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    [NSURLConnection connectionWithRequest:request delegate:self]; //Should be: [[NSURLConnection alloc]initiWithRequest:request delegate:self]; ...however the instance of NSURLConnection is never used, which results in an "entity unsed" error. 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 

    data = [[NSMutableData alloc]init]; // mutable data dictionary is allocated and initilized 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData { 

    [data appendData:theData]; // append 'theData' to the mutable data dictionary 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 

    //JSON foundation object returns JSON data from a foundation object. Assigned returned data to a dictionary 'json'. 
    NSDictionary* jsonData = [NSJSONSerialization JSONObjectWithData:data 
                  options:kNilOptions error:0]; 

    self.dropletsArray = [jsonData objectForKey:@"droplets"]; //dictionary of arrays 
    NSLog(@"Droplets %@", self.dropletsArray); 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
    // If the application is unable to connect to The Digital Ocean Server, then display an UIAlertView 
    UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Unable to connect to The Digital Ocean Server, please ensure that you are connected via either WIFI or 3G." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil]; 

    [errorView show]; 

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; // Turn of the network activity indicator 
} 

@end 

DropletsList.h

@class Droplets; 

    @interface DropletsList : UITableViewController 

    - (Droplets *) modelDroplets; 

    @end 

DropletsList.m

#define RGB(r, g, b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1] 

    @interface DropletsList() 

    //Private properties 
    @property (strong, nonatomic) Droplets *modelDroplets; 
    @property (strong, nonatomic) NSArray *tableData; 

    @end 

@implementation DropletsList 

@synthesize tableData; 

- (id)initWithStyle:(UITableViewStyle)style 
{ 
    self = [super initWithStyle:style]; 
    if (self) { 
     // Custom initialization 
     NSLog(@"get my data from model"); 
    } 
    return self; 
} 

- (Droplets *) modelDroplets 
{ 
    if (!_modelDroplets) _modelDroplets = [[Droplets alloc]init]; 
    return _modelDroplets; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    _modelDroplets = [[Droplets alloc]init]; 
    self.tableData = [_modelDroplets dropletsArray]; 
    [_modelDroplets getDropletsList]; 

    [self.tableView reloadData]; // reload the droplets table controller 

} 


- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

#pragma mark - Table view data source 


- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView { 

    return 1; // Return the number of sections. 

} 


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

    return [_modelDroplets.dropletsArray count]; // Return the number of rows in the section. 
} 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // The cell identified by "dropletsList", is assiged as the UITableViewCell 
    UITableViewCell *cell = [tableView 
          dequeueReusableCellWithIdentifier:@"dropletsList"]; 

    //NSLog(@"Droplets Name: %@",self.dropletsArray); 

    // The UITableView text label is assigned the contents from 'dropletsArray', with the object key "name"- name of the droplet 
    cell.textLabel.text=[[tableData objectAtIndex:indexPath.row]objectForKey:@"name"]; 

    // The UITableView text detail label is assigned the contents from 'dropletsArray', with the object key "status"- status of the droplet 
    cell.detailTextLabel.text=[[tableData objectAtIndex:indexPath.row]objectForKey:@"status"]; 

    //Evalulate the status of each droplet, setting the colour appropriate to the staus 
    if ([[[tableData objectAtIndex:indexPath.row] objectForKey:@"status"] isEqualToString:@"active"]) { 

     //Set the detail text label colour 
     cell.detailTextLabel.textColor = RGB (35,179,0); 
    } 
    return cell; 

} 

@end 

基本上我的表不填充。請有人可以幫忙嗎?

+0

是numberOfSectionsInTableView,numberOfRowsInSection和的cellForRowAtIndexPath被調用的方法? – 2013-05-01 09:07:56

+0

嗨The Dude,回答你的問題,是從UIButton調用表視圖。事實上,我有這個應用程序最初的工作,但NSRUL連接委託方法,其中所有位於我的ViewController'DropletsList'。然後,我把模型分解成了一個單獨的課程。 – 2013-05-01 11:42:05

+0

我認爲你應該遵循Anupdas的建議,它似乎與網絡連接有關。 – 2013-05-01 12:23:36

回答

0
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    _modelDroplets = [[Droplets alloc]init]; 
    self.tableData = [_modelDroplets dropletsArray]; 
    [_modelDroplets getDropletsList]; 

    [self.tableView reloadData]; // reload the droplets table controller 

} 

在這種方法中,您正在從web服務中獲取液滴。它是異步的,到tableView重新加載數據時,它可能還沒有完成獲取數據。你需要有一個回調,它會在完成webservice時重新加載tableView。

編輯:

創建Droplets一個類的方法來獲取所有數據

//Droplets.h 
typedef void (^NSArrayBlock)(NSArray * array); 
typedef void (^NSErrorBlock)(NSError * error); 

//Droplets.m 
+ (void)getDropletsWithCompletion:(NSArrayBlock)arrayBlock onError:(NSErrorBlock)errorBlock 
{ 
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:kDigialOceanApiURL]; 
    [urlRequest setHTTPMethod:@"GET"]; 
    [urlRequest setCachePolicy:NSURLCacheStorageNotAllowed]; 
    [urlRequest setTimeoutInterval:30.0f]; 
    [urlRequest addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

    [NSURLConnection sendAsynchronousRequest:urlRequest 
             queue:[NSOperationQueue mainQueue] 
          completionHandler:^(NSURLResponse *response, NSData *responseData, NSError *error) { 

           if (error) { 
            errorBlock(error); 
           }else{ 
            NSError *serializationError = nil; 
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData 
                         options:NSJSONReadingAllowFragments 
                          error:&serializationError]; 

            arrayBlock(json[@"droplets"]); 
           } 

          }]; 

} 

//DropletsList.h 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    [Droplets getDropletsWithCompletion:^(NSArray *array) { 
      self.modelDroplets = droplets; 
      [self.tableView reloadData]; 
    } onError:^(NSError *error) { 

      UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; 
      [alert show]; 
    }]; 

} 

免責聲明:測試和認證:)

+0

嗨Anupdas,謝謝你的評論,你能給我一個關於我的課程的「回調」的例子嗎? – 2013-05-01 11:38:46

+0

@ user1992953我編輯了我的答案。它會讓你開始。 – Anupdas 2013-05-01 12:50:52

+0

Anupdas,你是明星!所以只是爲了澄清,顯然你的例子使用了一個類的方法,因此如果我想符合NSURLConnectionDelegate,我需要做什麼不同呢? – 2013-05-01 15:57:45

相關問題