-[__NSArrayM objectAtIndex:]: index 6 beyond bounds [0 .. 4]'
我有点问题如何显示(null)
如果我没有数据。
这是代码
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
if ([[bookList objectAtIndex:indexPath.item]quiz_url]==[[bookList objectAtIndex:6]quiz_url]) {// This one is problem, I have `objectAtIndex:` only 0 - 5 .
// quiz_all = [[bookList objectAtIndex:indexPath.item]quiz_url];
_getQuiz6 = [[bookList objectAtIndex:6]quiz_url];
NSLog(@" test quiz6 = %@",_getQuiz6); //It's possible? Can I print `(null)` if no data.
}
...
和
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [bookList count];
}
我在webservice上没有数据[[bookList objectAtIndex:6]quiz_url]
。
答案 0 :(得分:0)
你有很多方法可以解决这个问题。处理它的一种方法是使用“占位符”对象填充内容,例如NSNull
。或者您可以修改Book
对象并添加isLoaded
等属性。
无论你选择哪种方法,然后(坚持使用NSNull
);
- (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
// Whatever code you have
Book *book = [bookList objectAtIndex:indexPath.item];
// NSNull is a singleton, you can safely do pointer comparison
if (book == [NSNull null])
{
// Show loading or something in the cell
cell.loadingOrSomething = YES;
// Return the cell here
return cell;
}
// book wasn't NSNull, then proceed with the rest of stuff
NSURL *url = [book quiz_url];
cell.loadingOrSomething = NO;
return cell;
}
答案 1 :(得分:-1)
如果需要,您可以使用类别。标题中的某处包括:
@interface NSArray (custom)
-(id)quizURLAtIndex:(int)index;
@end
并在.m文件中添加:
@implementation NSArray (custom)
-(id)quizURLAtIndex:(int)index{
if(index >= self.count) return nil;
else return [[self objectAtIndex:index] quiz_url];
}
@end
从现在开始,无论何时,您都可以拨打[bookList quizURLAtIndex:indexPath.item]
而不是[[bookList objectAtIndex:indexPath.row] quiz_url]