这里有两种方法 . 第一个有jsonData . 第二个负责制作jsonObject .
postsFromJSONData调用postsFromJsonObject
当数据未保存在Core数据中时,不会出现问题 .
问题是当我们从Core数据中获取并且已经保存了 .
然后,返回该获取的记录 .
在point2(它在代码中标记)我打印post.title它有 Value .
但是在第1点,当我返回从postsFromJsonObject返回的post.title时,它是空的!
static func postsFromJSONData(data: NSData, inContext context: NSManagedObjectContext) -> PostResult {
do {
...
var finalPosts = [Post]()
for postJSON in jsonDictionary1 {
if let post = postFromJSONObject(postJSON, inContext: context) {
finalPosts.append(post)
print(post.title)
// Point1 ***********************************
print(finalPosts[0].title) // It prints an empty string.
}
}
return .Success(finalPosts)
} catch let error {
return .Failure(error)
}
}
postFromJsonObject方法:
private static func postFromJSONObject(json: [String:AnyObject], inContext context: NSManagedObjectContext) -> Post? {
guard let
...
postTitle = json["title"] as? String,
postBody = json["body"] as? String else {
return nil
}
var post: Post!
let fetchRequest = NSFetchRequest(entityName: "Post")
fetchRequest.predicate = NSPredicate(format: "id = %@", "\(postID)")
do {
let foundRecordsArray = try! mainQueueContext.executeFetchRequest(fetchRequest) as! [Post]
print(foundRecordsArray.count)
if foundRecordsArray.count > 0 {
print("it is in coreData")
post = foundRecordsArray.first!
post.title = postTitle
} else{
print("It is new")
context.performBlockAndWait() {
post = NSEntityDescription.insertNewObjectForEntityForName("Post", inManagedObjectContext: context) as! Post
post.title = postTitle
...
}
}
} catch {
print("error in post from jsonObject!")
}
// Point2 ************************************************
print(post.title) // it prints the title correctly.
return post
}
在第2点:
在回复帖子之前我打印了它们 . 当它不在核心数据时:
(entity:Post; id:0xd000000001040002 x-coredata:// D01327F6-B7A8-45E0-A728-2A13985BA8D6 / Post / p65; data:{body =“quia et suscipit \ nsuscipit recusandae consequuntur expedita et cum \ nreprehenderit molestiae ut ut quas totam \ nnostrum rerum est autem sunt rem eveniet architecto“; id = 1; title =”sunt aut facere repellat provident occaecati excepturi optio reprehenderit“; userId = 1;})
当它在核心数据时
(entity:Post; id:0x7fc363d1fc30 x-coredata:/// Post / t25999BB8-1F6A-4C4D-B217-3CAB2C8E50722; data:{body =“quia et suscipit \ nsuscipit recusandae consequuntur expedita et cum \ nreprehenderit molestiae ut ut quas totam \ nnostrum rerum est autem sunt rem eveniet architecto“; id = 1; title =”sunt aut facere repellat provident occaecati excepturi optio reprehenderit“; userId = 1;})
不同的是以下几行:
x-coredata:/// Post / t25999BB8-1F6A-4C4D-B217-3CAB2C8E50722 x-coredata:// D01327F6-B7A8-45E0-A728-2A13985BA8D6 / Post / p65
它可能已经成功了!
我还要提一下,当我将postFromJSONObject代码移动到postFromJSONData时,问题就解决了,所以我认为问题是从我返回帖子的角度来看!