0

我有一个 UITableView 我添加为子视图,self.view它在

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

这是我的代码:

接口(在 CRFeedViewController.m 中)
@property (assign) BOOL dataIsLoaded;

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(dataIsLoaded == YES)
    {
        return [self.items count];
    }
    else {
        return 1;
    }
}

// Return a cell for the index path
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cell";

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Cell label
    cell.textLabel.text = @"Tweet";

    if (cell == nil) {
        cell = [[UITableViewCell alloc] init];
    }

    return cell;
}

- (void)getTimeLine {
    ACAccountStore *account = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    [account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
     {
         if (granted == YES)
         {
             NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];

             if ([arrayOfAccounts count] > 0)
             {
                 ACAccount *twitterAccount = [arrayOfAccounts lastObject];

                 NSURL *requestURL = [NSURL URLWithString:@"http://api.twitter.com/1/statuses/home_timeline.json"];

                 NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
                 [parameters setObject:@"20" forKey:@"count"];
                 [parameters setObject:@"1" forKey:@"include_entities"];

                 SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:requestURL parameters:parameters];

                 postRequest.account = twitterAccount;

                 [postRequest performRequestWithHandler: ^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
                  {
                      self.items = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];

                      if (self.items.count != 0) {
                          dataIsLoaded = YES;
                          [self.tableView reloadData];
                      }
                      else {
                          NSLog(@"No items");
                      }
                  }];
             }
         } else {
             NSLog(@"No access");
         }
     }];
}

- (void) viewWillAppear:(BOOL)animated
{
    [self getTimeLine];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    /**
     *  TABLE VIEW
     *  Add subview of the table
     */
    self.items = [NSArray arrayWithObjects:@"test", nil];

    CGRect tableViewRect = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    UITableView *tableView = [[UITableView alloc] initWithFrame:tableViewRect style:UITableViewStylePlain];

    tableView.dataSource = self;

    [self.view addSubview:tableView];
}

编辑

这是我的完整代码,很抱歉我还不明白这一切,我还是很新。

。H

//
//  CRFeedViewController.h
//  Twitter
//
//  Created by Cody Robertson on 6/27/13.
//  Copyright (c) 2013 Cody Robertson. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <Accounts/Accounts.h>
#import <Social/Social.h>

@interface CRFeedViewController : UIViewController  <UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSArray *items;

@end

.m

//
//  CRFeedViewController.m
//  Twitter
//
//  Created by Cody Robertson on 6/27/13.
//  Copyright (c) 2013 Cody Robertson. All rights reserved.
//

#import "CRFeedViewController.h"

#import "CRComposeViewController.h"
#import "CRSearchViewController.h"

@interface CRFeedViewController ()

@property (assign) BOOL dataIsLoaded;

- (void) composeTweet: (id) sender;
- (void) searchTweets: (id) sender;

- (void) getTimeLine;

@end

@implementation CRFeedViewController

@synthesize dataIsLoaded;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        /**
         *  NAV BAR
         *  Add icon and button to nav bar
         */

        // Add Twitter Icon as Title
        UIImageView *UINavTitleLogo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UINavBarLogo.png"]];
        UINavTitleLogo.contentMode = UIViewContentModeScaleAspectFill;
        self.navigationItem.titleView = UINavTitleLogo;

        // Add Search & Compose Icon
        UIImage *UISearchNavButton = [UIImage imageNamed:@"Search.png"];
        UIBarButtonItem *CRSearchNavButton = [[UIBarButtonItem alloc] initWithImage:UISearchNavButton style:UIBarButtonItemStylePlain target:self action:@selector(searchTweets:)];

        UIImage *UIComposeNavButton = [UIImage imageNamed:@"Compose.png"];
        UIBarButtonItem *CRComposeNavButton = [[UIBarButtonItem alloc] initWithImage:UIComposeNavButton style:UIBarButtonItemStylePlain target:self action:@selector(composeTweet:)];

        NSArray *UINavItems = @[CRComposeNavButton, CRSearchNavButton];
        self.navigationItem.rightBarButtonItems = UINavItems;

        [[UINavigationBar appearance] setTitleTextAttributes:@{
            UITextAttributeTextColor: [UIColor whiteColor]
        }];

        /**
         *  TAB BAR
         *  Add icon and label to task bar
         */
        UIImage *CRFeedTabBarIcon = [UIImage imageNamed:@"Home.png"];
        UITabBarItem *CRFeedTabBarItem = [[UITabBarItem alloc] initWithTitle:@"Home" image:CRFeedTabBarIcon tag:0];
        self.tabBarItem = CRFeedTabBarItem;
    }
    return self;
}

- (void) composeTweet:(id)sender
{
    /**
     *      PUSH VIEW TO COMPOSE
     *      Load the compose view
     */
    CRComposeViewController *CRCompose = [[CRComposeViewController alloc] init];
    CRCompose.title = @"New Tweet";
    [self.navigationController pushViewController:CRCompose animated:YES];
}

- (void) searchTweets:(id)sender
{
    /**
     *      PUSH VIEW TO SEARCH
     *      Load the search view
     */
    CRSearchViewController *CRSearch = [[CRSearchViewController alloc] init];
    CRSearch.title = @"Search";
    [self.navigationController pushViewController:CRSearch animated:YES];
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(dataIsLoaded == YES)
    {
        return [self.items count];
    }
    else {
        return 1;
    }
}

// Return a cell for the index path
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cell";

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Cell label
    cell.textLabel.text = @"Tweet";

    if (cell == nil) {
        cell = [[UITableViewCell alloc] init];
    }

    return cell;
}

- (void)getTimeLine {
    ACAccountStore *account = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    [account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
     {
         if (granted == YES)
         {
             NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];

             if ([arrayOfAccounts count] > 0)
             {
                 ACAccount *twitterAccount = [arrayOfAccounts lastObject];

                 NSURL *requestURL = [NSURL URLWithString:@"http://api.twitter.com/1/statuses/home_timeline.json"];

                 NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
                 [parameters setObject:@"20" forKey:@"count"];
                 [parameters setObject:@"1" forKey:@"include_entities"];

                 SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:requestURL parameters:parameters];

                 postRequest.account = twitterAccount;

                 [postRequest performRequestWithHandler: ^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
                  {
                      self.items = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];

                      if (self.items.count != 0) {
                          dataIsLoaded = YES;
                          [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
                      }
                      else {
                          NSLog(@"No items");
                      }
                  }];
             }
         } else {
             NSLog(@"No access");
         }
     }];
}

- (void) viewWillAppear:(BOOL)animated
{
    [self getTimeLine];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    /**
     *  TABLE VIEW
     *  Add subview of the table
     */
    self.items = [NSArray arrayWithObjects:@"test", nil];

    CGRect tableViewRect = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    UITableView *tableView = [[UITableView alloc] initWithFrame:tableViewRect style:UITableViewStylePlain];

    tableView.delegate = self;
    tableView.dataSource = self;

    [self.view addSubview:tableView];
}

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

@end
4

4 回答 4

0

如果错误发生在numberOfRows方法中,那么罪魁祸首很可能是:

[self.items count];

最有可能导致错误的情况是如果self.items没有count方法。在你的viewDidLoad中,你将它设置为一个NSArray,它确实有一个count方法。但是,您还设置了另一个位置self.items

self.items = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];

该方法的结果很可能没有count方法,因此不是NSArray,但您将其存储在定义为 的变量中NSArray

在上面的那一行之后,输入以下代码:

NSLog(@"Class: %@", NSStringFromClass([self.items class]));

如果输出不是NSArray,您很可能遇到了编程错误。


此外,您似乎正在使用多个线程来读取/写入同一个变量。如果不对这些属性实现某种线程安全,这通常不是一个好主意。

于 2013-06-29T03:24:34.640 回答
0

reloadData您应该在主线程上调用该方法:

[self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];

不确定这是否会导致您的崩溃,但您需要使用重用标识符初始化您的单元格:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier;

我建议您在应用程序崩溃时发布在 Xcode 中记录的跟踪。它将更好地理解您的应用程序崩溃的原因。

于 2013-06-29T01:37:46.993 回答
0

首先添加委托,以便运行这些方法。不要忘记在您的 .h 中订阅委托。

视图控制器.h

@interface ViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) NSArray *items;

// 在你的 viewDidLoad

tableView.dataSource = self;
tableView.delegate = self;
于 2013-06-29T01:31:29.103 回答
0

即使您没有数据,您也会返回 1 个单元格。你应该返回 0

于 2013-06-29T02:20:12.193 回答