Я новичок в Objective-C. Я потратил бесчисленные часы на то, чтобы получить пустой стол, я в отчаянии в этот момент. Я загружаю данные twitter через вызов JSON, используя их API. Я храню все в NSDictionary, запустите цикл for, чтобы выбрать только «текстовые» значения. Я храню фильтрованный словарь в объекте, который позже я использую в инициализации TableView. Я создал подкласс UItableViewCell для моей пользовательской ячейки. Мои данныеИсточники и делегаты, похоже, хорошо связаны (это то, что я думаю, по крайней мере) Мне трудно найти свою проблему. Если кто-то может помочь мне, пожалуйста.Заполнение пользовательского TableViewCell из Twitter с помощью JSON Serialization
#import "ViewController.h"
#import "myCell.h"
#import <TwitterKit/TwitterKit.h>
@interface ViewController()
@end
@implementation ViewController
@synthesize myTableView;
NSMutableArray *tweetObject;
NSDictionary *dictionary;
NSString *name;
NSString *text;
- (void)viewDidLoad {
tweetObject = [[NSMutableArray alloc] init];
[super viewDidLoad];
self.myTableView.dataSource = self;
self.myTableView.delegate = self;
text = @"text";
[[Twitter sharedInstance] logInGuestWithCompletion:^(TWTRGuestSession *guestSession, NSError *error) {
if (guestSession) {
// make API calls that do not require user auth
NSString *statusesShowEndpoint = @"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=goofernator";
NSError *clientError;
NSURLRequest *request = [[[Twitter sharedInstance] APIClient]
URLRequestWithMethod:@"GET"
URL:statusesShowEndpoint
parameters:0
error:&clientError];
if (request) {
[[[Twitter sharedInstance] APIClient]
sendTwitterRequest:request
completion:^(NSURLResponse *response,
NSData *data,
NSError *connectionError) {
if (data) {
// handle the response data e.g.
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:data
options:0
error:&jsonError];
for (NSDictionary *dataDict in json) {
NSString *text = [dataDict valueForKeyPath: @"text"];
dictionary = [NSDictionary dictionaryWithObjectsAndKeys:text,@"bodytext",nil];
[tweetObject addObject:dictionary];
}
}
else {
NSLog(@"Error: %@", connectionError);
}
}];
}
else {
NSLog(@"Error: %@", clientError);
}
} else {
NSLog(@"error: %@", [error localizedDescription]);
}
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return tweetObject.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
myCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell=[[myCell alloc]initWithStyle:
UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
NSDictionary *tmpDict = [self.tweetObject objectAtIndex:indexPath.row];
cell.txtLblOutput.text = [tmpDict objectForKey:text];
[tableView reloadData];
return cell;
}
@end
Здесь вы можете увидеть, как мой раскадровка, вместе взятые, и ссылки я использую
http://postimg.org/image/79w7pqmu3/
http://postimg.org/image/ixq9kabyz/
спасибо за ваш быстрый ответ, перемещение [tableView reloadData]; для запроса обработчика завершения была решена проблема с пустой таблицей. Однако данные, которые я пытаюсь загрузить, пока не отображаются. Он определенно загружается успешно (способен к NSLog), но я думаю, что я делаю что-то неправильно, добавляя его в новый NSdictionary, потому что tableview возвращает null. Я не согласен, я должен читать и учиться, это именно то, что я пытаюсь сделать, это мой второй день, когда я делаю/вижу цель-С, и я рад, что люди здесь полезны. –
Хорошо, я понял ... нашел правильный способ вывода массива в строки. –