RLMException报错:属性'productos'需定义包含类型协议的求助
Pedido and V3Producto Association Hey there, let's tackle this Realm error you're facing. The exception you're seeing—'Property 'productos' requires a protocol defining the contained type - example: RLMArray'—is telling you exactly what's missing: your productos property in the Pedido class isn't clearly defining what type of objects it holds.
What's the Issue?
Realm's RLMArray (its container type for collections of objects) isn't like a regular NSArray—it needs explicit knowledge of the object type it's storing to handle persistence, queries, and relationships correctly. When you declare a RLMArray property without specifying the contained object type via its protocol, Realm throws this error because it doesn't know how to interact with that collection.
The Fix
Since you already have your V3Producto class set up as a RLMObject subclass, you just need to update your Pedido class to properly type the productos property. Here's how:
Declare the
productosproperty with the correct Realm container syntax
In yourPedidointerface, use theRLMArraytype with both the generic type annotation and the required protocol (which matches yourV3Productoclass name):#import <Realm/Realm.h> #import "V3Producto.h" @interface Pedido : RLMObject // Add your other Pedido properties here (e.g., order ID, date, etc.) @property RLMArray<V3Producto *><V3Producto> *productos; @end @implementation Pedido // Optional: If you want to index the productos property for faster queries, add this: + (NSArray *)indexedProperties { return @[@"productos"]; } @endKey Details to Note
- The
<V3Producto>protocol is automatically generated by Realm for yourRLMObjectsubclass—you don't need to define it yourself. - Make sure you've imported
V3Producto.hin yourPedidoclass file, otherwise the compiler won't recognize the protocol. - This syntax tells Realm that the
productosproperty is a collection ofV3Productoobjects, which resolves the type ambiguity that was causing the exception.
- The
Why This Works
By specifying the contained type via the protocol, Realm can enforce that only V3Producto objects are added to the productos collection, and it knows how to persist, load, and query those objects correctly.
Once you make this change, your RLMException should be resolved, and you'll be able to work with the Pedido ↔ V3Producto relationship as expected.
内容的提问来源于stack exchange,提问作者Ignacio Oroná

