Ala*_*lan 11 iphone block objective-c cs193p ios
我试图设计一个帮助方法,它将检索UIManagedDocument,然后打开并返回它,以便我可以从我的应用程序中的几个地方访问相同的UIManagedDocument.
由于我对块不太熟悉,因此我遇到了异步性问题.理想情况下,事件的顺序是这样的:
我可以通过某种方式传递原始块吗?
到目前为止,这是我的代码.任何想法都非常感谢,谢谢.
// This is a dictionary where the keys are "Vacations" and the objects are URLs to UIManagedDocuments
static NSMutableDictionary *managedDocumentDictionary = nil;
// This typedef has been defined in .h file:
// typedef void (^completion_block_t)(UIManagedDocument *vacation);
// The idea is that this class method will run the block when its UIManagedObject has opened
@implementation MyVacationsHelper
+ (void)openVacation:(NSString *)vacationName usingBlock:(completion_block_t)completionBlock
{
// Try to retrieve the relevant UIManagedDocument from managedDocumentDictionary
UIManagedDocument *doc = [managedDocumentDictionary objectForKey:vacationName];
// Get URL for this vacation -> "<Documents Directory>/<vacationName>"
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:vacationName];
// If UIManagedObject was not retrieved, create it
if (!doc) {
// Create UIManagedDocument with this URL
doc = [[UIManagedDocument alloc] initWithFileURL:url];
// Add to managedDocumentDictionary
[managedDocumentDictionary setObject:doc forKey:vacationName];
}
// If document exists on disk...
if ([[NSFileManager defaultManager] fileExistsAtPath:[url path]])
{
[doc openWithCompletionHandler:^(BOOL success)
{
// Can I call the completionBlock from above in here?
// How do I pass back the opened UIDocument
}];
} else {
[doc saveToURL:url
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success)
{
// As per comments above
}];
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用completionBlock(doc)执行该块.
[doc openWithCompletionHandler:^(BOOL success)
{
// Can I call the completionBlock from above in here?
// How do I pass back the opened UIDocument
completionBlock(doc);
}];
Run Code Online (Sandbox Code Playgroud)
假设您在将调用openVacation方法的类中实现了以下方法:
-(void)vacationOpened:(UIManagedDocument *)vacation
{
NSLog(@"My Vacation: %@", vacation.description);
}
Run Code Online (Sandbox Code Playgroud)
调用openVacation方法的示例代码行将是:
[MyVacationsHelper openVacation:@"MyVacation1" usingBlock:^(UIManagedDocument *vacation){
[self vacationOpened:vacation];
}];
Run Code Online (Sandbox Code Playgroud)
插入符后的(UIManagedDocument*vacation)意味着当您使用括号表示法执行块时 - 如在completionBlock(doc)中 - ,您需要列出(UIManagedDocument*)作为参数.该参数的值将在指定的块内称为休假.我在上面的块代码示例中所做的是在我当前的类(self)中调用一个方法并将参数传递给该方法,以便我可以根据需要使用它(我只是在这里做了一个NSLog以确保它工作) .
| 归档时间: |
|
| 查看次数: |
6344 次 |
| 最近记录: |