使用Core Data和Magical Record创建实例变量 [英] Creating a Instance Variable using Core Data and Magical Record

查看:201
本文介绍了使用Core Data和Magical Record创建实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,在给定类中的给定方法中,我可以创建一个由Core Data和Magical Record管理的自定义变量的实例,其中包含以下行

Currently in a given method within a given class I can create a instance of a custom variable managed by Core Data and Magical Record with the following line

AViewController.m

List *list = [List MR_createInContext:_managedObjectContext];

然后我可以像这样设置列表的属性:

I can then set the list's properties like so:

list.name = @"FooBar Name";

我的问题:在 AViewController.h 我可以做以下 -

My question: In AViewController.h can I do the following -

@interface AViewController : UIViewController {
    /* Define Local List Var for AViewController class */
    List *list;
}

然后在 .m

viewdidload {
list = [List MR_createInContext:_managedObjectContext];
}

someCustomMethod {
  list.name = @"FooBar Name";

  [_managedObjectContext MR_save];
}


推荐答案

但是如果你试图从输入元素创建新对象(也许在按钮点击),只有通过一次又一次运行应用程序才会创建新对象。
我的意思是如果你的 someCustomMethod 被再次调用,同样的对象将被重写的值。 (这是很好,如果这是你想要的。)

Your code should work. But if you are trying to create new objects from input elements (maybe on button click), new objects will be created only by running the application again and again. What I mean is if your someCustomMethod is called again and again the same object will get rewritten with the values. (Which is fine if that is what you want.)

但是如果你想创建新的对象,你应该在对象内再次初始化。您应该使用以下代码:

But if you want to create new objects you should initialize it again inside the object. i.e. you should use the below code:

viewdidload {
list = [List MR_createInContext:_managedObjectContext];
}

someCustomMethod {
  list.name = @"FooBar Name";

  [_managedObjectContext MR_save];

  list = [List MR_createInContext:_managedObjectContext]; //add this line

}

每次调用 someCustomMethod 时,将创建保存的新对象。

So this way old object will be saved and new object will be created each time someCustomMethod is called.

这篇关于使用Core Data和Magical Record创建实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆