Core Data属性返回0的问题 [英] Issue with Core Data attribute returning 0

查看:242
本文介绍了Core Data属性返回0的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Core Data不保存NSString。


/ p>

目前在我的最新应用程序中遇到了Core Data的一个奇怪问题。基本上,我完成的是解析JSON和添加每个对象到相应的属性下的Core Data。这工作正常,从我可以看到从NSLogs我已经设置到位。但是,当在UITableView中显示其中一个值时,它总是返回0,因为一些未知的原因。



这里是我用来存储对象进入核心数据实体。

   - (void)syncNotes {

UIApplication * app = [ UIApplication alloc];
app.networkActivityIndi​​catorVisible = YES;

NSDictionary * params = [NSDictionary dictionaryWithObject:authToken forKey:@api_key];

[[LRResty client] get:@http://notacio.us/api/noteparameters:params withBlock:^(LRRestyResponse * response){

if (response.status == 200){
NSLog(@成功连接\ n%@,[response asString]);

//创建SBJSON对象以解析JSON
SBJSON * parser = [[SBJSON alloc] init];

//将JSON字符串解析为对象 - 假设[response asString]是JSON数据的NSString
NSDictionary * object = [parser objectWithString:[response asString] error:nil];

NSFetchRequest * noteFetch;
NSManagedObject * newNote;

appDelegate =(NotaciousAppDelegate *)[[UIApplication sharedApplication] delegate];

NSEntityDescription * entity = [NSEntityDescription entityForName:@NoteinManagedObjectContext:appDelegate.managedObjectContext];
NSArray * fetchedNotes;

NSArray * notes = [object valueForKey:@result];
for(NSDictionary * singleNote in notes){

noteFetch = [[NSFetchRequest alloc] init];
[noteFetch setEntity:entity];
NSPredicate * pred = [NSPredicate predicateWithFormat:@ID ==%@,[singleNote objectForKey:@note id]];
[noteFetch setPredicate:pred];

NSError * fetchError = nil;
fetchedNotes = [appDelegate.managedObjectContext executeFetchRequest:noteFetch error:& fetchError];

if(fetchError!= nil){
NSLog(@syncNotes fetchError =%@,details =%@,fetchError,fetchError.userInfo);
}
if([fetchedNotes count] == 0){


NSString * notelocked = [singleNote objectForKey:@note locked];

NSString * notecreated = [singleNote objectForKey:@note created];
NSString * noteupdated = [singleNote objectForKey:@note updated];
NSString * notetitle = [singleNote objectForKey:@note title];
NSString * notesummary = [singleNote objectForKey:@note summary];
NSString * noteid = [singleNote objectForKey:@note id];
NSString * notecontent = [singleNote objectForKey:@note content];

NSLog(@Note Title:%@,notetitle);
NSLog(@Note Summary:%@,notesummary);
NSLog(@Note ID:%@,noteid);
NSLog(@Note Content:%@,notecontent);
NSLog(@Note Created:%@,notecreated);
NSLog(@Note Updated:%@,noteUpdated);
NSLog(@Note Locked:%@,notelocked);


newNote = [NSEntityDescription insertNewObjectForEntityForName:@NoteinManagedObjectContext:appDelegate.managedObjectContext];
[newNote setValue:notecontent forKey:@content];
[newNote setValue:notesummary forKey:@summary];
[newNote setValue:notetitle forKey:@title];
[newNote setValue:noteid forKey:@ID];
[newNote setValue:notecreated forKey:@created];
[newNote setValue:noteUpdated forKey:@updated];
[newNote setValue:notelocked forKey:@locked];

NSError * error = nil;
if(![appDelegate.managedObjectContext save:& error]){
NSLog(@Unresolved error%@,%@,error,[error userInfo]);
abort();
}


}

}

[noteFetch release];
app.networkActivityIndi​​catorVisible = NO;

}

if(response.status == 404){
NSLog(@FAIL\\\
%@,[response asString]);
app.networkActivityIndi​​catorVisible = NO;
}

}];

}



因此NSLog从我输出代表从JSON解析并将被存储的对象如下。

  2011-03-31 10:52: 23.334 Notacious [755:707]注意:标题:商务草案
2011-03-31 10:52:23.335 Notacious [755:707]注意摘要:确保你得到一个到pez结束w
2011-03-31 10:52:23.336 Notacious [755:707] Note ID:676
2011-03-31 10:52:23.336 Notacious [755:707]是大约150个词,其余的是报告的正文。
2011-03-31 10:52:23.337 Notacious [755:707]注意:创建时间:2011年2月24日17:02:13 -0800 2011
2011-03-31 10:52:23.339 Notacious [ 755:707]注意更新:Thu Feb 24 17:10:43 -0800 2011
2011-03-31 10:52:23.339 Notacious [755:707]注意锁定:0

正如你所看到的,有一些值设置。但是,我的问题在这里有点怪异。当设置UITableViewCell并且我尝试获取更新的值时,它返回0.我正在调用这样的值:

  NSManagedObject * managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath]; 

NSLog(@%@,[[managedObject valueForKey:@title] description]);
NSLog(@%@,[[managedObject valueForKey:@updated] description]);

NSString * updated = [[managedObject valueForKey:@updated] description];
NSString * parsedDate = [NSDate getNoteTime:updated];

NSLog(@Before Format:%@,updated);
NSLog(@After Format:%@,parsedDate);

其中记录以下内容:

  2011-03-31 10:56:22.544 Notacious [755:707]商务草稿
2011-03-31 10:56:22.545 Notacious [755:707] 0
2011-03-31 10:56:22.548 Notacious [755:707] time0
2011-03-31 10:56:22.549 Notacious [755:707] note:0,current:1301531182
2011-03-31 10:56:22.550 Notacious [755:707]之前格式:0
2011-03-31 10:56:22.550 Notacious [755:707] **

正如你所看到的,更新的字符串返回0.任何人都可以知道为什么这将会发生?



EDIT



我试图用创建valueForKey,而你永远不会猜到发生了什么。它工作完全正常。所以我唯一能想到的是,如果当我们将值保存到Core Data属性,它不能正确保存。这是奇怪的,因为创建和更新的属性都是NSStrings。实际上,Core Data实体中的所有内容都是NSStrings。

解决方案

最可能的解释是,由字典返回的对象和实体期望的对象。例如。 noteUpdated 应该是一个日期,但在代码中没有强制执行。如果您尝试使用字符串值设置日期无法解析,则日期可能会报告值为零。您应该检查由字典返回的类,以查看它们是否适合于它们分配给的属性。



此外,此描述的使用是不必要的:

  NSLog @%@,[[managedObject valueForKey:@title] description]); 

...因为NSLog无论如何都会发送描述消息。你在这里是描述返回的字符串的描述。这可能或可能不会准确地反映对象的值。只需使用:

  NSLog(@%@,[managedObject valueForKey:@title]); 

在排除故障时,我建议直接打印受管对象,如下所示:

  NSLog(@%@,manageObject); 

...这将让你看到一切处于更原始的状态。


Possible Duplicate:
Core Data not saving NSString.

Hey all!

Currently experiencing a weird issue with Core Data in my latest application. Basically what I'm accomplishing is that of parsing JSON and adding each object into Core Data under the respective attribute. This works fine as far as I can see from the NSLogs I have set in place. However, when it comes to displaying one of the values in a UITableView, it always returns 0 for some unknown reason.

Here is the function that I am using to store the objects into the Core Data entity.

-(void)syncNotes {

UIApplication *app = [UIApplication alloc];
app.networkActivityIndicatorVisible = YES;

NSDictionary *params = [NSDictionary dictionaryWithObject:authToken forKey:@"api_key"]; 

[[LRResty client] get:@"http://notacio.us/api/note" parameters:params withBlock:^(LRRestyResponse *response){

    if(response.status == 200) {
        NSLog(@"Successful Connection \n%@", [response asString]);

        // Create SBJSON object to parse JSON
        SBJSON *parser = [[SBJSON alloc] init];

        // parse the JSON string into an object - assuming [response asString] is a NSString of JSON data
        NSDictionary *object = [parser objectWithString:[response asString] error:nil];

        NSFetchRequest *noteFetch;
        NSManagedObject *newNote;

        appDelegate =(NotaciousAppDelegate *) [[UIApplication sharedApplication] delegate];

        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Note" inManagedObjectContext:appDelegate.managedObjectContext];
        NSArray *fetchedNotes;

        NSArray *notes = [object valueForKey:@"result"];
        for (NSDictionary *singleNote in notes){

            noteFetch=[[NSFetchRequest alloc] init];
            [noteFetch setEntity:entity];
            NSPredicate *pred=[NSPredicate predicateWithFormat:@"ID==%@",[singleNote objectForKey:@"note id"]];
            [noteFetch setPredicate:pred];

            NSError *fetchError=nil;
            fetchedNotes=[appDelegate.managedObjectContext executeFetchRequest:noteFetch error:&fetchError];

            if (fetchError!=nil) {
                NSLog(@"syncNotes fetchError=%@,details=%@",fetchError,fetchError.userInfo);
            }
            if ([fetchedNotes count]==0) {


                NSString *notelocked = [singleNote objectForKey:@"note locked"];

                NSString *notecreated = [singleNote objectForKey:@"note created"];
                NSString *noteupdated = [singleNote objectForKey:@"note updated"];
                NSString *notetitle = [singleNote objectForKey:@"note title"];
                NSString *notesummary = [singleNote objectForKey:@"note summary"];
                NSString *noteid = [singleNote objectForKey:@"note id"];
                NSString *notecontent = [singleNote objectForKey:@"note content"];

                NSLog(@"Note Title: %@",notetitle);
                NSLog(@"Note Summary: %@",notesummary);
                NSLog(@"Note ID: %@",noteid);
                NSLog(@"Note Content: %@",notecontent);
                NSLog(@"Note Created: %@",notecreated);
                NSLog(@"Note Updated: %@",noteupdated);
                NSLog(@"Note Locked: %@",notelocked);


                newNote = [NSEntityDescription insertNewObjectForEntityForName:@"Note" inManagedObjectContext:appDelegate.managedObjectContext];
                [newNote setValue:notecontent forKey:@"content"];
                [newNote setValue:notesummary forKey:@"summary"];
                [newNote setValue:notetitle forKey:@"title"];
                [newNote setValue:noteid forKey:@"ID"];
                [newNote setValue:notecreated forKey:@"created"];
                [newNote setValue:noteupdated forKey:@"updated"];
                [newNote setValue:notelocked forKey:@"locked"];

                NSError *error = nil;
                if (![appDelegate.managedObjectContext save:&error]) {
                    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
                    abort();
                }


            }

        }

        [noteFetch release];
        app.networkActivityIndicatorVisible = NO;

    }

    if (response.status == 404) {
        NSLog(@"FAIL\n%@", [response asString]);
        app.networkActivityIndicatorVisible = NO;
    }

}];

}

So the NSLog's from me outputting the strings that represent that of the objects parsed from the JSON and that are going to be stored are as follows.

2011-03-31 10:52:23.334 Notacious[755:707] Note Title: Business Draft
2011-03-31 10:52:23.335 Notacious[755:707] Note Summary: Make sure you get one to Pez by end of w
2011-03-31 10:52:23.336 Notacious[755:707] Note ID: 676
2011-03-31 10:52:23.336 Notacious[755:707] Note Content: Business Draft
Conclusion is about 150 words, the rest is for the body of the report.
2011-03-31 10:52:23.337 Notacious[755:707] Note Created: Thu Feb 24 17:02:13 -0800 2011
2011-03-31 10:52:23.339 Notacious[755:707] Note Updated: Thu Feb 24 17:10:43 -0800 2011
2011-03-31 10:52:23.339 Notacious[755:707] Note Locked: 0

As you can see, there are values set for everything. However, my issue gets a little weird here. When setting up the UITableViewCell and I try to grab the value for updated, it returns 0. I am calling the value like this:

NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];

NSLog(@"%@",[[managedObject valueForKey:@"title"] description]);
NSLog(@"%@",[[managedObject valueForKey:@"updated"] description]);

NSString *updated = [[managedObject valueForKey:@"updated"] description];
NSString *parsedDate = [NSDate getNoteTime:updated];

NSLog(@"Before Format: %@",updated);
NSLog(@"After Format: %@",parsedDate);

Which in turn logs the following:

2011-03-31 10:56:22.544 Notacious[755:707] Business Draft
2011-03-31 10:56:22.545 Notacious[755:707] 0
2011-03-31 10:56:22.548 Notacious[755:707] time0
2011-03-31 10:56:22.549 Notacious[755:707] note:0, current:1301531182
2011-03-31 10:56:22.550 Notacious[755:707] Before Format: 0
2011-03-31 10:56:22.550 Notacious[755:707] After Format: ********

As you can see, the updated string returns 0. Can anyone shed any light as to why this would be happening?

EDIT

I tried to do it with the created valueForKey instead, and you'll never guess what happened. It worked perfectly fine. So the only thing I can think of is if when we're saving the value to the Core Data attribute, it isn't saving properly. Which is weird, because both the created and updated attributes are NSStrings. Actually, everything in the Core Data entity are NSStrings.

解决方案

The most likely explanation is that you have a mismatch between the object classes returned by the dictionary and the objects expected by the entity. E.g. noteUpdated is supposed to be a date but there is nothing in the code that enforces that. If you try to set a date using a string value it cannot parse, the date may report a value of zero. You should check the classes returned by the dictionaries to see if they are appropriate for the attributes they are assigned to.

Also, this use of description is unnecessary:

NSLog(@"%@",[[managedObject valueForKey:@"title"] description]);

... because NSLog sends the description message anyway. What you have here is the description of a string returned by description. That may or may not accurately reflect the value of the object. Just use:

NSLog(@"%@",[managedObject valueForKey:@"title"]);

When troubleshooting, I would recommend printing the managed objects directly like so:

NSLog(@"%@",manageObject);

... which will let you see everything in it's more raw state.

这篇关于Core Data属性返回0的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆