看来我的代码运行正常,但如果没有Twitter帐户存储在设备中,应用程序将因此错误而崩溃由于未捕获的异常'NSRangeException'终止应用程序,原因:' * - [__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
或类似内容,而不是让它崩溃?
答案 0 :(得分:2)
将您的if
更改为仅在您的数组中包含对象时执行,您可以使用count
if (twitterAccounts.count)
答案 1 :(得分:0)
如果没有先查看是否有帐户,请致电ACAccount *currentAccount = [twitterAccounts objectAtIndex:0];
。
一种选择是改变:
if (twitterAccounts != nil)
为:
if (twitterAccounts.count) {
// process the account
} else {
// show alert
}
答案 2 :(得分:0)
考虑更改原始代码
if (twitterAccounts != nil)
到
if (twitterAccounts != nil && twitterAccounts.count)