【发布时间】:2017-02-12 17:39:32
【问题描述】:
我正在尝试将 CoreData 值保存到一个数组中,以便以后在表格视图中显示它。但到目前为止,尽管应用程序中有数据,但日志显示该数组为空(null)。我不明白为什么会这样。有人可以帮我吗?代码如下:
@interface TableViewController ()
@property (strong) NSMutableArray *locations;
@end
@implementation TableViewController
- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate respondsToSelector:@selector(managedObjectContext)]){
context = [delegate managedObjectContext];
}
return context;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.dataSource = self;
NSError *error;
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Spot"];
self.locations = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
[self.tableView reloadData];
NSLog(@"%@ Places are: ", _locations);
}
编辑:AppDelegate.m:
+ (AppDelegate *)sharedDelegate {
return (AppDelegate*)[UIApplication sharedApplication].delegate;
}
- ( NSURLSession * )getURLSession
{
static NSURLSession *session = nil;
static dispatch_once_t onceToken;
dispatch_once( &onceToken,^{
NSURLSessionConfiguration *configuration =[NSURLSessionConfiguration defaultSessionConfiguration];
session = [NSURLSession sessionWithConfiguration:configuration];
});
return session;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"https:franciscocosta.net/lisbon-spots"]];
NSURLSessionDataTask *task = [[self getURLSession] dataTaskWithRequest:request completionHandler:
^( NSData *data, NSURLResponse *response, NSError *error ){
dispatch_async( dispatch_get_main_queue(),^{
NSError *error;
NSArray *mainLocations = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
for(NSDictionary *dict in mainLocations) {
[Spot spotWithDict:dict];
}
});
}];
[task resume];
return YES;
}
【问题讨论】:
-
为什么忽略
error参数?为什么locations声明为不可变但分配为可变? -
好的,已编辑,但日志仍然为空...
-
您仍然忽略错误。里面有什么吗?
-
刚刚记录了错误,它也是空的...
-
是
managedObjectContextnil?设置断点并检查引用?
标签: ios objective-c core-data