删除实体关系Coredata

时间:2015-10-19 11:15:13

标签: ios objective-c xcode core-data relational-database

使用CoreData,我有一个名为Wishlist的实体,它与实体调用WishlistProduct有很多关系。 (这种关系被称为'愿望清单')。

product.wishlists = nil删除了Wishlist和WishlistProduct之间的关系。 WishlistListProduct在多个Wishlist中引用,product.wishlists = nil删除所有引用,如何删除对特定愿望清单的引用

        WishlistProduct *product;

        NSManagedObjectContext *context = [self managedObjectContext];
        product.wishlists = nil;   //  Removes all relationships

         [context save:nil];

我认为像currentWishlist.product.wishlists = nil,任何帮助都会很棒

3 个答案:

答案 0 :(得分:0)

由于您拥有多对多关系,因此您无法使用wishList.product来引用特定产品,因为每个列表中有多个产品。

您首先必须过滤/获取相关产品,然后将其愿望清单设置为nil

将特定NSSetProduct的多对多关系(类型nil)设置为products可能会有所帮助,但您应该对其进行测试。您应该检查所有反向关系是否也按预期更新。如果不是这种情况,请遍历列表并从每个列表的NSManagedObject关系中删除产品。

实际上,Xcode会在您生成- (void)addListsObject:(List *)value; - (void)removeListsObject:(List *)value; - (void)addLists:(NSSet *)values; - (void)removeLists:(NSSet *)values; 子类时为您创建适当的访问者来添加和删除多对象。他们看起来像这样

<html>
<head>
  <script>
    function foo() {
      latestKnownScrollY = window.pageYOffset;
      console.log(latestKnownScrollY);
    }
  </script>
</head>
<body onscroll="foo()">
</body>
</html>

答案 1 :(得分:0)

你必须得到产品的所有威士忌并删除威士忌。

NSMutableSet *set = [product mutableSetValueForKey:@"wishlists"];
[set removeObject:wishlist];

或者相反。

如果您生成了NSManagedObject的子类,则可以使用Core Data Generated Accessors。

[product removeWishlistsObject:wishlist];

或者相反。

答案 2 :(得分:0)

我仍然不确定你想要完成什么,但这里有我能想到的四种可能性的例子。

- (void)removeWishlist:(NSManagedObject*)wishlist
           fromProduct:(NSManagedObject*)product {
    [[product mutableToManyRelationshipForKey:@"wishlists"] removeObject:wishlist];
}

- (void)removeProduct:(NSManagedObject*)product
         fromWishlist:(NSManagedObject*)wishlist {
    [[wishlist mutableToManyRelationshipForKey:@"products"] removeObject:product];
}

- (void)removeAllProductsFromWishlist:(NSManagedObject*)wishlist {
    [wishlist setValue:nil forKey:@"products"];
}

- (void)removeAllWishlistsFromProduct:(NSManagedObject*)product {
    [product setValue:nil forKey:@"wishlists"];
}

其中mutableToManyRelationshipForKey:NSManagedObject上的类别方法,它根据关系是否有序返回相应的可变集合。

- (id)mutableToManyRelationshipForKey:(NSString*)key {
    NSRelationshipDescription *relationship =
        [[self.entity relationshipsByName] objectForKey:key];
    return relationship.isOrdered
        ? [self mutableOrderedSetValueForKey:key]
        : [self mutableSetValueForKey:key];
}

当然,如果您使用Xcode生成的代码或mogenerator之类的代码,所有这一切都会更容易。

相关问题