使用核心数据保存CGPoint

Using core data to save CGPoint

我正在使用核心数据来保存添加到标签的文本,这些标签中的每一个都可以移动。我目前正在用一个字符串实体保存文本,效果很好。我将如何使用核心数据在移动时保存视图的 CGPoint,然后在再次打开视图时将其加载回保存的位置。

代码如下

 -CGPoint firstTouchPoint;

//xd = distance between image center and my touch center
float xd;
float yd;

@implementation BlankViewController
-(BOOL)prefersStatusBarHidden
{
    return YES;
}
@synthesize name;


-(NSManagedObjectContext *)managedObjectContext {
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}

(IBAction)save:(id)sender {


    NSManagedObjectContext *context = [self managedObjectContext];


    if (self.name) {
        [self.name setValue:self.nameTextField.text forKey:@"name"];
        [self.name setValue:self.Label1.text forKey:@"label1"];
        [self.name setValue:self.Label2.text forKey:@"label2"];
}
else{
        // Create a new managed object
        NSManagedObject *newName = [NSEntityDescription insertNewObjectForEntityForName:@"Maths" inManagedObjectContext:context];
        [newName setValue:self.nameTextField.text forKey:@"name"];
        [newName setValue:self.Label1.text forKey:@"label1"];
        [newName setValue:self.Label2.text forKey:@"label2"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
 if (self.name) {
        [self.nameTextField setText:[self.name valueForKey:@"name"]];
        [self.Label1 setText:[self.name valueForKey:@"label1"]];
        [self.Label2 setText:[self.name valueForKey:@"label2"]];  }}


Code to move the views:


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch* bTouch = [touches anyObject];
    if ([bTouch.view isEqual:[self imgTest]]) {
        firstTouchPoint = [bTouch locationInView:[self view]];
        xd = firstTouchPoint.x - [[bTouch view]center].x;
        yd = firstTouchPoint.y - [[bTouch view]center].y;
        [self.view bringSubviewToFront:self.imgTest];
    }
    else if ([bTouch.view isEqual:[self imgTest2]]) {
        firstTouchPoint = [bTouch locationInView:[self view]];
        xd = firstTouchPoint.x - [[bTouch view]center].x;
        yd = firstTouchPoint.y - [[bTouch view]center].y;
        [self.view bringSubviewToFront:self.imgTest2];
    }
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch* mTouch = [touches anyObject];
    if (mTouch.view == [self imgTest]) {
        CGPoint cp = [mTouch locationInView:[self view]];
        [[mTouch view]setCenter:CGPointMake(cp.x-xd, cp.y-yd)];
    }
    else if (mTouch.view == [self imgTest2]) {
        CGPoint cp = [mTouch locationInView:[self view]];
        [[mTouch view]setCenter:CGPointMake(cp.x-xd, cp.y-yd)];
    }
}

如果您只需要在您的实体中存储一个 CGPoint,我会向您的实体添加两个必需的浮点属性(比如 xy)并存储点像那样。

使用最新的 Xcode,您可以让它为您生成模型对象,这比处理普通 NSManagedObject 更容易。使用该模型对象,添加定义 point 属性 的类别也很容易,您可以使用该类别将核心数据属性转换为 CGPoint,反之亦然。