Swift CoreData将字符串与实体进行比较

时间:2015-06-17 08:32:05

标签: ios swift core-data

我正在浏览NSArray并发送我在Core Data上的内容,如下所示:

let json2:NSArray = NSJSONSerialization.JSONObjectWithData(data.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! [NSArray]

        for dict in json2 {
            var apps = [String]()

            //Creation du lien vers la base SQLite
            let entityDescription = NSEntityDescription.entityForName("Task", inManagedObjectContext: self.context!)
            let nTask = Task(entity: entityDescription!, insertIntoManagedObjectContext: self.context)


            let request = NSFetchRequest()
            request.entity = entityDescription
            var error: NSError?
            var objects = self.context?.executeFetchRequest(request, error: &error)


            if let summary = dict["summary"] as? String{
                nTask.summary = summary
            }


            if let description = dict["description"] as? String{
                nTask.detail = description
            }


            if let context = dict["context"] as? String{
                nTask.context = context
            }


            if let due = dict["due"] as? String {
                nTask.date = due
            }else{
                nTask.date = "No Ending Date"
            }

            if let status = dict["status"] as? String{
                nTask.status = status
            }

            if let responsible = dict["responsible"] as? String{
                nTask.responsable = responsible
            }

            if let id = dict["id"] as? String{
                nTask.id = id
            }

            println(nTask)



            /*let match = objects![0] as! NSManagedObject
            let result = match.valueForKey("id") as! String
            println(result)

            if result != nTask.id{*/
                self.context?.save(nil)
            //}

发送效果很好,核心数据已填充,一切似乎都没问题。

评论的内容是我正在寻找的内容,以及目前尚无法发挥作用的内容。我想检查nTask.id是否为String," id" key,等于我的核心数据中已存在的任何ID"任务"在属性" id"。

我创建实体描述,请求和请求返回的内容,然后尝试与nTask.id进行比较,但它总是匹配,我总是访问我的self.context?.save(nil),我得到了双倍的我不想要它...... 0。 这就是我想要做的事情:

let entityDescription = NSEntityDescription.entityForName("Task", inManagedObjectContext: self.context!) //creation of the Entity Description for my Entity, "Task"
    let request = NSFetchRequest()
    request.entity = entityDescription //Creation of the request on the Entity "Task"
    var error: NSError?
    var objects = self.context?.executeFetchRequest(request, error: &error) //Results are sent to my variable objects
let match = objects![0] as! NSManagedObject 
    let result = match.valueForKey("id") as! String
    println(result)

    if result != nTask.id{ //try to compare what the request return with the nTask.id
        self.context?.save(nil)
    }

我做错了什么或者我错过了什么?我只想检查我的CoreData上是否已存在nTask.id,如果它不存在,请将完整的任务发送到我的CoreData。

感谢您的帮助。

问候。

1 个答案:

答案 0 :(得分:1)

您当前的代码会提取所有Task个对象,但只会比较结果数组中id的{​​{1}} objectsTask。因此,将无法检测到此阵列中其他位置的重复项。

稍微调整您的代码,首先检查是否存在具有相关id的现有Task。使用您拥有的获取请求但包含谓词来仅获取具有相关id的任何Task个对象。如果您得到0结果,请创建新的for dict in json2 { var apps = [String]() var nTask : Task //Creation du lien vers la base SQLite let entityDescription = NSEntityDescription.entityForName("Task", inManagedObjectContext: self.context!) if let relevantID = dict["id"] as? String { let request = NSFetchRequest() request.entity = entityDescription request.predicate = NSPredicate(format:"id == %@",relevantID) var error: NSError? var objects = self.context?.executeFetchRequest(request, error: &error) if objects!.count == 0 { nTask = Task(entity: entityDescription!, insertIntoManagedObjectContext: self.context) } else { // You need to decide: create a new object and delete the old // update the old object with the new attribute values, or // just ignore the new values // The following will update the existing Task object nTask = objects![0] as! Task } } else { // no `id` to match against, so just create a new Task nTask = Task(entity: entityDescription!, insertIntoManagedObjectContext: self.context) } // Now update the attribute values... if let summary = dict["summary"] as? String{ nTask.summary = summary } if let description = dict["description"] as? String{ nTask.detail = description } if let context = dict["context"] as? String{ nTask.context = context } if let due = dict["due"] as? String { nTask.date = due }else{ nTask.date = "No Ending Date" } if let status = dict["status"] as? String{ nTask.status = status } if let responsible = dict["responsible"] as? String{ nTask.responsable = responsible } if let id = dict["id"] as? String{ nTask.id = id } println(nTask) self.context?.save(nil) } 。如果您得到一个或多个结果:您需要决定如何处理,但下面的代码将更新现有对象的属性值:

public class Test {
            public static void main(String [] args)
        {

        String [] str ={ "10.20","30450","12.valid","100.200"};

            for(int i=0; i<str.length; i++)
            {
                if(str[i].indexOf(".") == -1)
                {
                    try
                    {
                        Integer.parseInt(str[i]);
                        System.out.println("its a valid int nummber : "+str[i]);
                    }
                    catch(NumberFormatException e)
                    {
                        System.out.println("its invalid number in string: "+str[i]);
                    }
                }
                else
                {
                    try
                    {
                        Double.parseDouble(str[i]);
                        System.out.println("its valid double number: "+str[i]);
                    }

                    catch(NumberFormatException e)
                    {
                        System.out.println("its invalid char in string : "+str[i]);
                    }
                }
            }
        }
    }

请注意,这应该有效,但效率不高。您可能需要阅读Apple核心数据编程指南section on "Efficiently importing data"以获得更有效的算法。