因此,我开始学习iOS的核心数据,并编写了这部分代码:
- (void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
id delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *objectContext = [delegate managedObjectContext];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Album"];
//An array of our sorted Album objects by date in ascending order
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]];
NSError *error = nil;
NSArray *fetchedAlbums = [objectContext executeFetchRequest:fetchRequest error:&error];
self.albums = [fetchedAlbums mutableCopy];
[self.tableView reloadData];
}我的问题是,这一行的目的是什么:
id delegate = [UIApplication sharedApplication].delegate;我知道,对于委托,您需要将特定对象的当前实例传递给委托属性,委托属性将该对象设置为另一个对象的委托。我的问题是当你这么做的时候:
id delegate = [UIApplication sharedApplication].delegate;将哪个对象传递给该delegate属性?sharedApplication方法返回我假设的应用程序的一个单例实例,然后您将获得该应用程序的单个实例的delegate属性。该委托是指在AppDelegate.h/AppDelegate.m文件中使用的同一个委托吗?
如果委托属性与在AppDelegate.h/AppDelegate.m文件中使用的属性相同,那么viewDidLoad方法中的AppDelegate.m文件中不应该有一行代码,在委托属性中传递AppDelegate.m的当前实例,类似于我们对tableView所做的操作
self.tableView.delegate = self. 在这行中,我不知道delegate属性是在哪里完成的:
id delegate = [UIApplication sharedApplication].delegate;发布于 2015-08-23 19:51:16
您不需要将AppDelegate指定为应用程序的委托,因为它是为您自动完成的。
在objective中,您可以查看main.m函数,其中可以找到提到您的AppDelegate类:
int main(int argc, char *argv[])
{
@autoreleasepool {
int retVal = UIApplicationMain(argc, argv, nil, @"AppDelegate");
return retVal;
}
}在此调用之后,系统将类AppDelegate的实例设置为应用程序的委托。
在Swift中,main.m缺少,这就是为什么在声明委托类之前总是有@UIApplicationMain的原因:
@UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {
}因为UIApplication.sharedApplication()是单例,所以UIApplication.sharedApplication().delegate总是返回AppDelegate的同一个实例。
因此,如果您从一个视图控制器修改AppDelegate中的某些属性,则可以确保其他视图控制器将访问修改后的版本。通过实现一个简单的计数器并检查始终可以读取最新的值,您可以轻松地验证它:)
https://stackoverflow.com/questions/32170600
复制相似问题