2017-02-12 76 views
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; 
} 
+0

爲什麼你忽略'error'參數?爲什麼'locations'被聲明爲不可變的,但被賦值爲mutable? – vadian

+0

好吧,它已被編輯,但日誌仍然爲空... – FuManchu

+0

您仍然無視錯誤。它包含任何東西嗎? – vadian

回答

0

你在哪裏創建核心數據堆棧。形成一個單身?在這種情況下,將創建的managedObjectContext的引用傳遞給appDelegate中的managedObjectContext屬性。

願你看看到堆棧創建的Marcus Zarra.或者蘋果的核心數據Programming Guide.