我正在使用新的iOS Spotify SDK。我需要为我的应用程序获取所有用户保存的曲目。结果是分页的。因此,我试图使用requestNextPageWithSession:callback:递归,直到我获取了所有页面。
首先,我首先要求保存曲目。这会成功返回第一页,因此如果有其他页面,我会调用getNextPage()
__block SPTListPage *allPages;
[SPTRequest savedTracksForUserInSession:session callback:^(NSError *error, SPTListPage *firstPage) {
if (!error) {
allPages = firstPage;
if (firstPage.hasNextPage) {
getNextPage(firstPage);
}
else {
// All tracks were in the first page
}
}
}];
getNextPage()被声明为上面的一个块,如下所示:
Block getNextPage;
getNextPage = ^(SPTListPage *page) {
[page requestNextPageWithSession:session callback:^(NSError *error, SPTListPage *nextPage) {
if (!error) {
[allPages pageByAppendingPage:nextPage];
if (nextPage.hasNextPage) {
getNextPage(nextPage);
}
else {
// Got all pages
}
}
}];
};
仅供参考 - 我已定义" Block"因此在全球范围内使用:
typedef void (^Block)();
问题是我第一次尝试在块中递归使用getNextPage(),它在该行上与EXC_BAD_ACCESS崩溃。堆栈跟踪没有帮助,但看起来像getNextPage被释放了。希望有人解决类似的问题。
答案 0 :(得分:1)
您必须保存对块的引用,否则在执行到达范围结束时将清除它。您可以在类上创建一个包含它的属性。
@property (nonatomic, copy) Block block;
或者,您可以使用方法。
- (void)fetchNextPage:(SPTListPage *)page {
[page requestNextPageWithSession:session callback:^(NSError *error, SPTListPage *nextPage) {
if (!error) {
[allPages pageByAppendingPage:nextPage];
if (nextPage.hasNextPage) {
[self fetchNextPage:nextPage];
}
else {
// Got all pages
}
}
}];
}