开发者

Efficient Core Data Recursion

开发者 https://www.devze.com 2023-03-29 01:00 出处:网络
Context I have a Core Data entity called \"LPFile\" that represents a file on disk. It has an optional relationship to itself that allows files to \"import\" each other, like so:

Context

I have a Core Data entity called "LPFile" that represents a file on disk. It has an optional relationship to itself that allows files to "import" each other, like so:

imports<<---开发者_如何学C->>importedBy

Question

Now, suppose I have this situation with Files 1, 2, 3, and 4:

File 1 is importedBY 2 and 3. Files 2 & 3 are importedBY 4. What I want to know is: if I start at file 1, what's the most efficient approach for finding the "base" or "end" file of this relationship (in this case, that's file 4)? I can write a simple recursive function that looks at each entity in the importedBy relationship, and follows the chain until it finds an entity with zero entities in the importedBy relationship, but I wanted to see if Core Data has a pre-baked method to do this.

Thanks!


Core Data has no pre-baked method to find a root. So your way of looping through it is fine.


Altough this questions has been answered, I solved a similiar problem on a tree made by same entities by adding an attribute called with much fantasy "breadcrumb" and filling that at runtime so that if I have entity model

X {
 name NSString
 breadcrumb NSString
 to-many X relationship
}

A,B,C,D,E like that:

A-->B
 -->C-->D
 -->E

I end up with this:

A {
 breadcrumb /A 
 relationship B,C,E
}


B {
 breadcrumb /A/B
 relationship nil
}     

C {
 breadcrumb /A/C
 relationship D
} 

D {
 breadcrumb /A/C/D
 relationship nil
} 

E {
 breadcrumb /A/D
 relationship nil
} 

I can say that indexing breadcrumb, make things faster, and I can do regex search. Important, when I have an entity I can easily find its root without cycling. Of course I had some mechanism to avoid loop and uniqueness of breadcrumb, based on 'name' attribute.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号