I'm completing the CS193 Stanford course, and am using Core Data to store tweets as part of a Twitter client.
However, when I find a hashmention that is existing, I want to increment the hash.count representing how many matches I have, but no matter how many matching hashmentions there are hash.count only ever stores 0 or 2 (i.e. the attribute is not functioning as persistent storage on the entity).
class HashMention: NSManagedObject {
static func findOrCreateHashMention(matching twitterInfo: Twitter.Mention, in context: NSManagedObjectContext) throws -> HashMention
{
let hash = HashMention (context: context)
let request : NSFetchRequest<HashMention> = HashMention.fetchRequest()
request.predicate = NSPredicate(format: "text =[cd] %@", twitterInfo.keyword)
do {
let matches = try context.fetch(request)
if matches.count > 0 {
//inc count
hash.count = Int32(Int(matches.count) + 1)
return hash
}
else{
hash.count = 0
print("zero hash:", twitterInfo.keyword)
hash.text = twitterInfo.keyword.lowercased()
return hash
}
}
catch{
//makes this function throw
throw error
}
}
}
So matches itself needed to be changed - but is in an array in the example above. Therefore the answer was the following:
do {
let matches = try context.fetch(request)
let mention = matches.first
if matches.count > 0 {
mention?.count = (mention?.count)! + 1
//.. more code