Objective-c Json解析空数组错误还是错误?

时间:2015-12-01 11:52:11

标签: ios arrays json xcode

当我用tableview解析json时,一切都很好,当有json项目但如果没有加载json项目,当我点击后退按钮给我这个错误。

    @interface MasterViewController ()

    @property (nonatomic, assign) NSInteger currentPage;
    @property (nonatomic, assign) NSInteger totalPages;
    @property (nonatomic, assign) NSInteger totalItems;
    @property (nonatomic, assign) NSInteger maxPages;

    @property (nonatomic, strong) NSMutableArray *activePhotos;
    @property (strong, nonatomic) NSMutableArray *staticDataSource;
    @property (nonatomic, strong) NSMutableArray *searchResults;

    @property (strong, nonatomic) IBOutlet UITableView *tableView;


    @end


            - (void)viewDidLoad
            {
                [super viewDidLoad];

                self.activePhotos = [[NSMutableArray alloc] init];
                self.searchResults = [[NSMutableArray alloc] init];
                self.staticDataSource = [[NSMutableArray alloc] init];


            }


            #pragma mark - Table View

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

    return  self.activePhotos.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    if (indexPath.row == [self.activePhotos count]) {
        cell = [self.tableView dequeueReusableCellWithIdentifier:@"LoadingCell" forIndexPath:indexPath];
        UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView *)[cell.contentView viewWithTag:100];
        [activityIndicator startAnimating];
    } else {
        NSDictionary *photoItem = self.activePhotos[indexPath.row];
        cell = [self.tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

        cell.textLabel.text = [photoItem objectForKey:@"name"];
        if (![[photoItem objectForKey:@"description"] isEqual:[NSNull null]]) {
            cell.detailTextLabel.text = [photoItem objectForKey:@"description"];
        }


    }


    return cell;
}



- (void)loadPhotos:(NSInteger)page
{



    NSString *userismim =[[NSUserDefaults standardUserDefaults] stringForKey:@"userisim"];


    NSArray* words = [userismim componentsSeparatedByCharactersInSet :[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString* nospacestring = [words componentsJoinedByString:@""];


    NSLog(@"%@",nospacestring);


    NSString *apiURL = [NSString stringWithFormat:@"http://bla.com/server/table.php?user=%@",nospacestring];

    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString:apiURL]
            completionHandler:^(NSData *data,
                                NSURLResponse *response,
                                NSError *error) {

                if (!error) {

                    NSError *jsonError = nil;
                    NSMutableDictionary *jsonObject = (NSMutableDictionary *)[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];

                    NSLog(@"%@",jsonObject);

                    [self.staticDataSource addObjectsFromArray:[jsonObject objectForKey:@"photos"]];

                    self.currentPage = [[jsonObject objectForKey:@"current_page"] integerValue];
                    self.totalPages  = [[jsonObject objectForKey:@"total_pages"] integerValue];
                    self.totalItems  = [[jsonObject objectForKey:@"total_items"] integerValue];

                    self.activePhotos = self.staticDataSource;

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

我认为当我快速点击后退按钮时json不会加载,并在我的表视图代码下面给出了这个错误。

//method for the players turn
    public static void playersTurn()
    {
        String playersCard = dealSingleCard();
        playerHand.add(playersCard);
        String playersActualHand = cardRepresentation(playersCard);
        System.out.println(playersActualHand);
        //System.out.println(playerHand);
        System.out.println(calculateHandValue(playerHand));
        Scanner in = new Scanner(System.in);
        System.out.println("Stick or Twist?");
        String stickOrTwist = in.next();
        String twist = "t";
        String stick = "s";
        //int total = 0;
        //int playerTotal = calculateHandValue(playerHand) + total;

        if (calculateHandValue(playerHand) < 21)
        {
            if (stickOrTwist .equalsIgnoreCase (twist));
            {
                dealSingleCard();

            }

        if (stickOrTwist .equalsIgnoreCase (stick))
                {
                    calculateWinner();
                }
        }

    }

谢谢你的一切。我需要你的帮助。

1 个答案:

答案 0 :(得分:1)

您正在显示活动指示符,该指示符将一直旋转,直到json加载。

如果你在json加载之前按下后退按钮,那么app会尝试为数组分配空引用,这是不可能的,所以它会抛出错误。

为避免这种情况,您可以在请求过后停止userInteraction,并在获得成功或失败响应后启用。

要停用互动,请添加

[[UIApplication sharedApplicaton] beginIgnoringInteractionEvents]  

NSURLSession *session = [NSURLSession sharedSession];

要再次启用,请添加:

 [[UIApplication sharedApplicaton] endIgnoringInteractionEvents]  

if (!error) {

这将解决我希望的问题。