2014-10-11 7 views
0

У меня проблема с моим столом. Я пытаюсь сделать программу, которая загружает детали задания из моей базы данных и перечисляет их. Просмотр таблицы по-прежнему пуст, представление подключено к определенному контроллеру, и я проверил, что идентификатор канала JSON и идентификатор ячейки в порядке. Мои строки ячеек также странны, строки строки продолжаются по правому краю, хотя я правильно выровнял объект tableview. У меня были аналогичные проблемы с моим предыдущим проектом, но я не знал, что случилось.Настольный вид еще пустой?

Вот часть кода (Source от: http://codewithchris.com/iphone-app-connect-to-mysql-database/)

JobViewer.m

@interface JobViewer() 
{ 
    NSMutableData *_downloadedData; 
} 
@end 

@implementation JobViewer 

- (void)downloadItems 
{ 
    // Getting json file 
    NSURL *jsonFileURL = [NSURL URLWithString:@"here is my correct URL"]; 

    //Making request 
    NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileURL]; 

    //Creating NSURLConnection with the request 
    [NSURLConnection connectionWithRequest:urlRequest delegate:self]; 

} 

#pragma mark NSURLConnectionDataProtocol Methods 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    //Initialize data 
    _downloadedData = [[NSMutableData alloc] init]; 

} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    //Append the data that was downloaded 
    [_downloadedData appendData:data]; 

} 

- (void)connectionDidFinishDownloading:(NSURLConnection *)connection 
{ 
    //Creating array for the information 
    NSMutableArray *_jobs = [[NSMutableArray alloc] init]; 

    // Parsing the JSON file 
    NSError *error; 
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error]; 

    //Looping through JSON objects and storing them into array 
    for (int i = 0; i < jsonArray.count; i++) 
    { 
     NSDictionary *jsonObject = jsonArray[i]; 

     //Creating a new object and getting data from JSON element 
     Job *newJob = [[Job alloc] init]; 
     newJob.jobid = jsonObject[@"Job_id"]; 
     newJob.companyid = jsonObject[@"Company_id"]; 
     newJob.customer = jsonObject[@"Customer"]; 
     newJob.phone = jsonObject[@"Phone"]; 
     newJob.email = jsonObject[@"Email"]; 
     newJob.address = jsonObject[@"Address"]; 
     newJob.city = jsonObject[@"City"]; 
     newJob.header = jsonObject[@"Header"]; 
     newJob.notes = jsonObject[@"Notes"]; 
     newJob.date = jsonObject[@"Date"]; 
     newJob.driver = jsonObject[@"Driver"]; 

     //Added question to array 
     [_jobs addObject:newJob]; 
    } 

    // Passing the done data and passing items back 
    if (self.delegate) 
    { 
     [self.delegate itemsDownloaded:_jobs]; 
    } 

} 

@end 

MainViewController.m

@interface MainViewController() 

{ 
    JobViewer *_jobViewer; 
    NSArray *_listObjects; 
} 

@end 

@implementation MainViewController 

- (void)viewDidLoad { 

    [super viewDidLoad]; 
    self.mainList.delegate = self; 
    self.mainList.dataSource = self; 

    _listObjects = [[NSArray alloc] init]; 
    _jobViewer = [[JobViewer alloc] init]; 
    _jobViewer.delegate = self; 
    [_jobViewer downloadItems]; 

} 

- (void)didReceiveMemoryWarning { 

    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 

} 

- (void)itemsDownloaded:(NSArray *)items 
{ 

    _listObjects = items; 
    [self.mainList reloadData]; 

} 

#pragma mark Table View Delegate Methods 
// You may remove this method 
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

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

    return _listObjects.count; 

} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    NSString *cellIdentifier = @"InfoCell"; 
    UITableViewCell *newCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

    Job *item = _listObjects[indexPath.row]; 

    newCell.textLabel.text = item.address; 

    //[newCell setBackgroundColor:[UIColor blackColor]]; 

    return newCell; 

} 

/* 
#pragma mark - Navigation 

// In a storyboard-based application, you will often want to do a little preparation before navigation 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
    // Get the new view controller using [segue destinationViewController]. 
    // Pass the selected object to the new view controller. 
} 
*/ 

@end 
+1

«строка линии продолжают по правому краю» Это интересно; что это значит? Я не знаю, что вы думаете о «строке строк»; вы можете опубликовать изображение и предоставить ссылку? – matt

+0

Привет! Это может быть только мой плохой английский, но вот картина «строк»: http://jessetakkinen.kapsi.fi/public_html/rows.png –

+0

в целом, я NSLog данных и hardcode словарь для вывода первой строки, которая получает меня через проблемы, упомянутые dfmuir. – timpone

ответ

0

Вы, вероятно, необходимо добавить «InfoCell» в качестве идентификатора повторного использования в вашей раскадровке.

+0

Благодарим вас за комментарий. Если вы имеете в виду поле Идентификатор в Инспекторе атрибутов, я уже установил его как «InfoCell». –

0

Возможно, ваш Tableview не распознает клетку, так что вы должны добавить ячейку в tableView в раскадровке и называется «Infocell»

Если вы не хотите, чтобы добавить ячейку в tableView в раскадровки, и у вас есть xib с вашей ячейкой. Вы можете позвонить в ваш ViewController этот метод:

[tableView registerNib:[UINib nibWithNibName:@"IndoCell" bundle:nil] forCellReuseIdentifier:@"IndoCell"]; 

, что если ваш СИБ называется «IndoCell.xib»

Смежные вопросы