1
我試圖將CoreData值保存到數組中以便稍後在表格視圖中顯示它。但到目前爲止,日誌告訴我數組是空的(空),儘管應用程序中有數據。我不明白爲什麼會發生這種情況。有人可以幫我嗎?下面的代碼:IOS/Objective-C:無法將CoreData值保存到NSArray中
@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'被聲明爲不可變的,但被賦值爲mutable? – vadian
好吧,它已被編輯,但日誌仍然爲空... – FuManchu
您仍然無視錯誤。它包含任何東西嗎? – vadian