【发布时间】:2013-10-10 04:08:28
【问题描述】:
看来我的代码运行良好,但如果设备中没有存储 Twitter 帐户,应用程序将崩溃并出现此错误 Terminating app due to uncaught exception 'NSRangeException', reason: '* - [__NSArrayI objectAtIndex:]: 空数组的索引 0 超出范围'
- (void)viewDidLoad
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
if (accountStore != nil)
{
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
if (accountType != nil)
{
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if (granted)
{
NSArray *twitterAccounts = [accountStore accountsWithAccountType:accountType];
if (twitterAccounts != nil)
{
ACAccount *currentAccount = [twitterAccounts objectAtIndex:0];
if (currentAccount != nil)
{
NSString *friendListString = @"https://api.twitter.com/1.1/friends/list.json?cursor=-1&skip_status=true&include_user_entities=false";
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:[NSURL URLWithString:friendListString] parameters:nil];
if (request != nil)
{
// 1.1 api requires a user to be logged in.
[request setAccount:currentAccount];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSInteger responseCode = [urlResponse statusCode];
if (responseCode == 200)
{
// ADD STUFFS HERE
}
[theCollectionView reloadData];
}
}
}];
}
}
}
}
else
{
NSLog(@"User did not grant access.");
}
}];
}
}
[super viewDidLoad];
}
我不知道为什么,因为我在创建后确实有如上所示的 nil 检查? ACAccount *currentAccount = [twitterAccounts objectAtIndex:0]; 如果在设备上找不到帐户,我将如何显示 UIAlertView 或类似内容,而不是让它崩溃?
【问题讨论】:
-
只需检查
if([twitterAccounts count] > 0)然后做你的工作,否则数组是空的。 -
检查
if(twitterAccounts!=nil)不会检查是否有可用的索引来获取对象。它只是检查twitterAccounts是否已初始化。虽然错误是说twitterAccounts中没有可用的索引 0。所以对于那个if ([twitterAccounts count] > index){NSLog(@"%@",twitterAccounts[index])}。就这样!!
标签: ios objective-c twitter