所以我在我的项目中使用 Magical Record,我正在尝试执行以下操作:
- (void)persistNewReadingWithOneA:(NSString *)oneA oneB:(NSString *)oneB{
NSManagedObjectContext *localContext = [NSManagedObjectContext MR_contextForCurrentThread];
FinalRead *reading1A = [FinalRead MR_createInContext:localContext];
reading1A.a1 = oneA;
reading1A.b1 = oneB;
[localContext MR_saveOnlySelfAndWait];
}
正如你所看到的,我坚持使用一个新条目,现在我需要能够通过添加它的属性来更新同一个条目。我尝试执行以下操作:
- (void)updateReadingWithTwoA:(NSString *)twoA twoB:(NSString *)twoB{
NSManagedObjectContext *localContext = [NSManagedObjectContext MR_contextForCurrentThread];
FinalRead *reading2A = [FinalRead MR_createInContext:localContext];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstname ==[c] %@ AND lastname ==[c] %@"];
FinalRead *finalRead = [FinalRead MR_findFirstWithPredicate:predicate inContext:localContext];
reading2A.a2 = twoA;
reading2A.b2 = twoB;
[localContext MR_saveOnlySelfAndWait];
}
有任何想法吗?
编辑:
我正在从 JSON 响应中获取数据,如下所示:
- (void)fetchedData:(NSData *)responseData {
if (self.buttonPressed){
//parse out the json data
NSError* error;
NSArray* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSString *string = [NSString stringWithFormat:@"%@", [json objectAtIndex:0]];
[self persistNewReadingWithOneA:string
oneB:nil];
}else{
//parse out the json data
NSError* error;
NSArray* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSString *string = [NSString stringWithFormat:@"%@", [json objectAtIndex:0]];
[self persistNewReadingWithOneA:nil
oneB:string];
}
}
然后像这样存储到新创建的对象:
- (void)persistNewReadingWithOneA:(NSString *)oneA oneB:(NSString *)oneB{
NSManagedObjectContext *localContext = [NSManagedObjectContext MR_contextForCurrentThread];
FinalRead *reading1A = [FinalRead MR_createInContext:localContext];
reading1A.a1 = oneA;
reading1A.b1 = oneB;
[localContext MR_saveOnlySelfAndWait];
}
然后 ViewController 推送到另一个询问另一个问题的问题,其中再次解析和存储更多 JSON,但进入刚刚在前一个 ViewController 中创建的 SAME 对象。我在 NSManagedObject 中有以下属性 PER 对象:
@interface FinalRead : NSManagedObject
@property (nonatomic, retain) NSString *a1;
@property (nonatomic, retain) NSString *b1;
@property (nonatomic, retain) NSString *a2;
@property (nonatomic, retain) NSString *b2;
@property (nonatomic, retain) NSString *a3;
@property (nonatomic, retain) NSString *b3;
@property (nonatomic, retain) NSString *a4;
@property (nonatomic, retain) NSString *b4;
@end
所以基本上,每次我更改一个新的 viewController 时,我都想添加到同一个对象,直到最终的 View 被使用。