我正在尝试将我的coredata中的选定对象从rootviewcontroller传递到编辑视图。正在传递所选对象,但在调用 theObject = selectedObject 后变为null。谁知道我做错了什么?
这是在edit.h
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#import "LearningAppDelegate.h"
@interface edit : UIViewController <UITextViewDelegate, UITableViewDelegate, UITableViewDataSource, UIActionSheetDelegate>{
UITableView *tableView;
NSManagedObject *theObject;
UITextView *messageView;
}
@property(nonatomic, retain) IBOutlet UITableView *tableView;
@property(nonatomic, retain) IBOutlet UITextView *messageView;
@property(nonatomic, retain) NSManagedObject *theObject;
-(id)initWithObject:(NSManagedObject *)selectedObject;
@end
这是在edit.m中:
-(id)initWithObject:(NSManagedObject *)selectedObject {
self = [super init];
if (nil == self) {
return nil;
}
NSLog(@"selectedObject: %@", selectedObject);
NSLog(@"selecetedObject.message: %@", [[selectedObject valueForKey:@"message"] description]);
theObject=selectedObject;
NSLog(@"theObject 1: %@", theObject);
NSLog(@"theObject.message 1: %@", [[theObject valueForKey:@"message"] description]);
return self;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
NSLog(@"theObject 2: %@", theObject);
NSLog(@"theObject.message 2: %@", [[theObject valueForKey:@"message"] description]);
messageView.text=[[theObject valueForKey:@"message"] description];
[super viewDidLoad];
}
答案 0 :(得分:2)
我真的很惊讶,不会为你崩溃。您将变量selectedObject分配给实例变量theObject,而不保留它供您自己使用。通过直接在赋值'theObject = selectedObject'中访问实例变量,您将绕过@property声明授予的行为。这意味着一旦selectedObject最终被dealloc'd,该对象将指向垃圾内存。
执行此操作的正确方法是将theObject = [selectedObject retain];在-initWithObject:方法和in -viewDidLoad中通过self.theObject而不仅仅是Object来访问它。
在我自己的用法中,我更喜欢给实例变量名称与实际属性名称不同,以避免混淆。例如:
@interface SomeClass : NSObject
{
@private
NSManagedObject *_theObject;
}
@property (nonatomic, retain) NSManagedObject *theObject;
...
@end
@implementation SomeClass
@synthesize theObject = _theObject
...
- (void)dealloc
{
[_theObject release], _theObject = nil;
[super dealloc];
}
@end
答案 1 :(得分:0)
我在桌面上只有Coredata的经验,但问题看起来与你的initWithObject方法有关。您实际上没有将新对象插入到托管对象上下文中。您应该使用此方法来创建新对象:
- (id)initWithEntity:(NSEntityDescription *)entity insertIntoManagedObjectContext:(NSManagedObjectContext *)context
作为伪代码的一个例子:
NSManagedObject *newObject = [[NSManagedObject alloc] initWithEntity:NSENTITYDESCRIPTION insertIntoManagedObjectContext:MANAGEDOBJECTCONTEXT];
[newObject setValue:@"VALUE_OF_SELECTED_OBJECT" forKey:@"APPROPRIATE_KEY"];
//REPEAT AS NECESSARY
[MANAGEDOBJECTCONTEXT save];
*未测试代码,忽略命名约定等。
保存非常重要。如果不这样做,对象将不会持续存在。