2

在 CoreData 中设置“To Many”关系并勾选“Ordered”框将您的属性定义为 NSOrderedSet。

有没有一种有效的方法可以在特定位置插入对象或上下移动对象?

或者我是否需要使用来自 NSOrderedSet 的数据创建一个 NSMutabledOrderedSet,插入或移动我的对象,然后将其转换回 NSOrderedSet?

还是我应该使用标准的 NSSet 并自己管理“位置”属性?

4

1 回答 1

1

CoreData 'Create NSManagedObject Subclasses...' 将生成许多方法供您用来操作您的有序集合。或者你可以对 Codegen 做同样的事情。

目标 C

@interface MyObject (CoreDataGeneratedAccessors)

- (void)insertObject:(NSManagedObject *)value inItemsAtIndex:(NSUInteger)idx;
- (void)removeObjectFromItemsAtIndex:(NSUInteger)idx;
- (void)insertItems:(NSArray<NSManagedObject *> *)value atIndexes:(NSIndexSet *)indexes;
- (void)removeItemsAtIndexes:(NSIndexSet *)indexes;
- (void)replaceObjectInItemsAtIndex:(NSUInteger)idx withObject:(NSManagedObject *)value;
- (void)replaceItemsAtIndexes:(NSIndexSet *)indexes withItems:(NSArray<NSManagedObject *> *)values;
- (void)addItemsObject:(NSManagedObject *)value;
- (void)removeItemsObject:(NSManagedObject *)value;
- (void)addItems:(NSOrderedSet<NSManagedObject *> *)values;
- (void)removeItems:(NSOrderedSet<NSManagedObject *> *)values;

@end

迅速

// MARK: Generated accessors for items
extension MyObject {

    @objc(insertObject:inItemsAtIndex:)
    @NSManaged public func insertIntoItems(_ value: NSManagedObject, at idx: Int)

    @objc(removeObjectFromItemsAtIndex:)
    @NSManaged public func removeFromItems(at idx: Int)

    @objc(insertItems:atIndexes:)
    @NSManaged public func insertIntoItems(_ values: [NSManagedObject], at indexes: NSIndexSet)

    @objc(removeItemsAtIndexes:)
    @NSManaged public func removeFromItems(at indexes: NSIndexSet)

    @objc(replaceObjectInItemsAtIndex:withObject:)
    @NSManaged public func replaceItems(at idx: Int, with value: NSManagedObject)

    @objc(replaceItemsAtIndexes:withItems:)
    @NSManaged public func replaceItems(at indexes: NSIndexSet, with values: [NSManagedObject])

    @objc(addItemsObject:)
    @NSManaged public func addToItems(_ value: NSManagedObject)

    @objc(removeItemsObject:)
    @NSManaged public func removeFromItems(_ value: NSManagedObject)

    @objc(addItems:)
    @NSManaged public func addToItems(_ values: NSOrderedSet)

    @objc(removeItems:)
    @NSManaged public func removeFromItems(_ values: NSOrderedSet)

}

否则是的,只需制作一个可变副本,根据需要进行操作,然后将其设置回 NSManagedObject。顺便说一句,您也不需要将其转换回非可变集

于 2016-09-23T04:51:35.880 回答