max*_*son 5 iphone core-data objective-c nscoding ios
我有两个实体,Chain和Step.Chain有一个属性steps,可以是多维Step实体数组,例如:
[
step,
step,
step,
[
step,
step
],
step
]
Run Code Online (Sandbox Code Playgroud)
每个Step对象都有content一个字符串属性.
如果我使用关系数据库,我只是将该数组存储为JSON,每个step都是step_id特定步骤.
我如何在Core Data中实现类似的功能?我认为我需要让这个Step类符合NSCoding协议,但那会是什么样子?我怎样才能使它只id在Chain.steps的最终值中存储它的等价物,即对它自己的引用?
编辑
下面的评论表明我nextStep在Step其他人之间包含了一对多关系(让我们称之为)Steps.然后我会使用这种关系从a中的一步到下一步Chain,因此Chain实体只需要包含Step序列中的第一步.这个问题是a Step可能属于多个Chain,因此它可能并不总是具有相同的nextStep值.
我不鼓励您序列化和反序列化包含 Core Data 对象的数组。您可以转换数组来保存URIRepresentation步骤的对象 ID,但如果从数据库中删除步骤,会发生什么情况?您的序列化数组仍然受到旧对象的污染。
这是我的建议。
https://github.com/LeoNatan/ChainStepsExample
我的模型设置如下:

Link是一个抽象实体。
为了方便使用,我定义了以下协议:
@protocol Link <NSObject>
//This is to make chain traversal easy - all links are guaranteed to have "steps".
- (NSOrderedSet*)steps;
@end
Run Code Online (Sandbox Code Playgroud)
为了创建,我添加了以下便捷工厂方法:
@interface Link : NSManagedObject <Link>
+ (id<Link>)linkWithStepsArray:(NSArray*)stepsArray inContext:(NSManagedObjectContext*)context;
+ (id<Link>)linkWithStepsOrderedSet:(NSOrderedSet*)stepsOrderedSet inContext:(NSManagedObjectContext*)context;
+ (id<Link>)linkWithStep:(Step*)step inContext:(NSManagedObjectContext*)context;
@end
Run Code Online (Sandbox Code Playgroud)
现在,链的创建和遍历都非常容易。
Step* step1 = [Step newObjectInContext:context];
step1.content = @"Wake up";
Step* step2_1 = [Step newObjectInContext:context];
step2_1.content = @"Go to school";
Step* step2_2 = [Step newObjectInContext:context];
step2_2.content = @"Learn new things";
Step* step3 = [Step newObjectInContext:context];
step3.content = @"Go to sleep";
NSOrderedSet* links = [NSOrderedSet orderedSetWithObjects:[Link linkWithStep:step1 inContext:context], [Link linkWithStepsArray:@[step2_1, step2_2] inContext:context], [Link linkWithStep:step3 inContext:context], nil];
[chain setLinks:links];
Run Code Online (Sandbox Code Playgroud)
最后遍历:
for(Chain* chain in chains)
{
NSLog(@"<chain %@>", chain.name);
for(id<Link> link in chain.links)
{
NSLog(@"\t<step>");
for(Step* step in link.steps)
{
NSLog(@"\t\t%@", step.content);
}
NSLog(@"\t</step>");
}
NSLog(@"</chain>\n\n");
}
Run Code Online (Sandbox Code Playgroud)
这允许您创建一个可管理的对象图,当任务被删除时,它将自动重建。
这是一个简单的例子。它只解决了一层深度。SingleStepLink您可以在orMultiStepLink和Link(而不是)之间建立无限深度的关系Step,而 leafs 与 具有最终关系Step。
| 归档时间: |
|
| 查看次数: |
956 次 |
| 最近记录: |