ios - 无法在 IOS7 中重新加载 TableView

标签 ios uitableview

我是 IOS 开发的新手,一直在为它苦苦挣扎。我想显示用户从我的服务器获得的电话列表,但 tableview 不显示项目。我从服务器很好地获取了数据,我认为 UItableView 的设置是正确的。这是我的代码:

STKPhoneHolderViewController.h

#import <UIKit/UIKit.h>
#import "STKSimpleHttpClientDelegate.h"

@interface STKPhoneHolderViewController : UITableViewController <UITableViewDataSource, STKSimpleHttpClientDelegate>
@property (strong, nonatomic) IBOutlet UITableView *phoneTable;
@property (strong, nonatomic) NSMutableArray *phoneArray;

@end

STKPhoneHolderViewController.m

@implementation STKPhoneHolderViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

    self.phoneTable.dataSource = self;
    self.phoneArray = [[NSMutableArray alloc]init];

    [self loadPhoneList];

}


#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return [self.phoneArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"PhoneCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

        STKPhoneHolder *phoneHolder = [self.phoneArray objectAtIndex:indexPath.row];
        [cell.textLabel setText:phoneHolder.userName];


    return cell;
}

#pragma Custom method
- (void) loadPhoneList
{

    self.phoneArray = [[NSMutableArray alloc]init];

    STKSimpleHttpClient *client = [[STKSimpleHttpClient alloc]init];
    client.delegate = self;

    NSString *userId = @"your_id_h";

    NSString *sUrl = [NSString stringWithFormat:@"%@%@?userid=%@",
                      MOBILE_API_URL,
                      PHONEHOLDER_URI,
                      userId];

    [client send:sUrl data:@""];
}

#pragma STKSimpleHttpClientDelegate
-(void) complete:(STKHttpResult*) result
{
     if (result.ok != YES){
         [STKUtility alert:result.message];
         return;
     }

    self.phoneArray = (NSMutableArray*)result.result;
    for (STKPhoneHolder *holder in self.phoneArray) {
        NSLog(@"%@", [holder description]);
    }

    [self.phoneTable reloadData];
    NSLog(@" isMainThread(%d)", [NSThread isMainThread] );
}


@end

STKSimpleHttpClient.m

#import "STKSimpleHttpClient.h"
#import "STKSimpleHttpClientDelegate.h"

@implementation STKSimpleHttpClient

NSMutableData *responseData;
STKHttpResult *httpResult;


void (^completeFunction)(STKHttpResult *);

- (void) send:(NSString*)url
         data:(NSString*)data
{
    httpResult = [[STKHttpResult alloc]init];
    dispatch_async(dispatch_get_main_queue(), ^{

        if ( data == nil) return;

        //Get request object and set properties
        NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: url]];
        //set header for JSON request and response
        [urlRequest setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        //set http method to POST
        [urlRequest setHTTPMethod:@"POST"];
        //set time out
        [urlRequest setTimeoutInterval:20];

        NSData *body = [data dataUsingEncoding:NSUTF8StringEncoding];
        //set request body
        urlRequest.HTTPBody = body;

        //connect to server
        NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
        if (conn==nil){
            //Do something
        }
    });
}

#pragma mark - NSURLConnection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    responseData = [[NSMutableData alloc] init];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    // Return nil to indicate not necessary to store a cached response for this connection
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable noow
    NSError *error;
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

    BOOL ok = [[json objectForKey:@"ok"] boolValue];
    NSString *message = [json objectForKey:@"message"];
    if (ok == NO) {
        [httpResult setError:message];
    } else {
        [httpResult setSuccess:[json objectForKey:@"result"]];
    }

    if (self.delegate !=nil) {
        [self.delegate complete:httpResult];
    }

    responseData = nil;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!
    // Check the error var
    if (self.delegate !=nil) {
        [self.delegate complete:[httpResult setError:@"Connection failed."]];
    }
}

STKPhoneHolder.m

#import <Foundation/Foundation.h>

@interface STKPhoneHolder : NSObject

@property NSString *deviceId;
@property NSString *userId;
@property NSString *userName;
@property NSString *msn;

- (id) initWithDeviceId:(NSString*)aDeviceId
                 userId:(NSString*)aUserId
            userName:(NSString*)aUserName
            msn:(NSString*)aMsn;

@end

日志:

2013-12-17 16:14:23.447 [5323:70b] {
    deviceId = 11111;
    email = "";
    msn = 11111111;
    role = "";
    userId = aaaaaa;
    userName = "Joshua Pak";
}
2013-12-17 16:14:23.448 [5323:70b] {
    deviceId = 22222;
    email = "";
    msn = 2222222;
    role = "";
    userId = bbbbb;
    userName = "Jasdf Pak";
}
2013-12-17 16:14:23.449 Stalker[5323:70b]  isMainThread(1)

我可以看到日志打印 phoneArray 有两个手机在 'complete' 方法中,但 tableview 只显示“无记录”。即使我调用了 reloadData 方法,Tableview 也不会再次呈现。我确保 [self.phoneTable reloadData] 在 Debug模式下被调用。 我还需要做什么?

最佳答案

尝试在主线程中调用reloadData

#pragma STKSimpleHttpClientDelegate
-(void) complete:(STKHttpResult*) result
{
     if (result.ok != YES){
         [STKUtility alert:result.message];
         return;
     }

    self.phoneArray = (NSMutableArray*)result.result;

    for (STKPhoneHolder *holder in self.phoneArray) {
            NSLog(@"%@", [holder description]);
        }

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.phoneTable reloadData];
    }
}

或者你可以使用performSelectorOnMainThread

[self.phoneTable performSelectorOnMainThread:@selector(reloadData)
                                 withObject:nil
                              waitUntilDone:NO];

我猜测 STKSimpleHttpClient 类正在不同的线程上调用完整的委托(delegate)函数,所有用户界面交互都应该从主线程调用。

尝试此代码,从完整的委托(delegate)函数中查看您所在的线程

NSLog(@" isMainThread(%d)", [NSThread isMainThread] );

关于ios - 无法在 IOS7 中重新加载 TableView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20623575/

相关文章:

ios - 应用内购买不起作用但得到产品响应

android - 如何使用 react-native-firebase 从 Firebase 动态链接接收查询参数?

ios - iOS是否延迟peripheralManager :didReceiveWriteRequests: and peripheralManager:didReceiveReadRequest:?

ios - UITableView 展开和折叠以显示部分或全部单元格

swift - 如何快速选择aTableView部分中的单元格

ios - 在 UITabBarController 上推送 UINavigationController 时 UITableViewCell 消失

ios - 由于 Yoga 错误,React Native iOS 构建失败

ios - 具有自定义数据源的 UITableViewController 不显示单元格

swift - Swift UITableView 中的渐变层

iphone - 如何在我的表格 View 中加载 20 x 20 条事件记录,其中事件按日期排序并将标题标题显示为事件日期