Xamarin.iOS中使用Realm创建对象报错问题求助
Hey there! I totally get how frustrating it is when following a tutorial step-by-step and hitting a random error—let's fix this Realm issue together.
错误原因
The error you're seeing happens because the tutorial you're using is from 2016, and Realm's .NET API has changed a lot since then. The generic CreateObject<T>() method that the tutorial uses no longer exists in newer versions of Realm for Xamarin; instead, only the non-generic CreateObject(string, object) overload is available, which is why you can't use type arguments with it.
解决方案
Luckily, creating objects in Realm is even simpler now! Here are two easy ways to replace that problematic code:
方法1:直接实例化对象并添加到Realm
You can directly create an instance of your Car class, then use realm.Add() to persist it within a write transaction. This is the recommended approach in modern Realm versions:
private void AddNewCar() { var realm = Realm.GetInstance(); realm.Write(() => { var newCar = new Car(); // 在这里设置车辆属性(可选) newCar.Brand = "Honda"; newCar.Model = "Civic"; realm.Add(newCar); }); }
方法2:使用Realm的泛型Add重载(简化写法)
If you want to combine instantiation and addition in one line, you can use the generic overload of Add():
private void AddNewCar() { var realm = Realm.GetInstance(); realm.Write(() => { var newCar = realm.Add(new Car()); // 同样可以在这里设置属性 newCar.Model = "Model 3"; }); }
额外检查
Your Car class looks correct already, but just to confirm:
- It properly inherits from
RealmObject - It has a public parameterless constructor (required by Realm)
- Its properties are auto-implemented (getters and setters)
Going forward, I'd recommend referencing the latest Realm .NET documentation instead of older tutorials—this will help you avoid version-related API mismatches.
内容的提问来源于stack exchange,提问作者Jamie Leech

