gpt4 book ai didi

cocoa - 使用 NSUserDefaults 存储图像坐标

转载 作者:行者123 更新时间:2023-12-03 17:42:04 24 4
gpt4 key购买 nike

我正在我的应用程序中移动图像,运行良好。问题是,当用户返回该 View 时,我想将图像保留在适当的位置。目前,我使用字符串来固定图像中心:

NSString *centre = NSStringFromCGPoint(image.center);

我有一个名为 theCentre 的 NSUserDefault 变量:

theCentre = [NSUserDefaults standardUserDefaults];

我尝试使用以下方法保存:

[theCentre setObject:centre forKey:@"centre"];

当我输出日志时,我得到以下内容:

{280, 320}

这太棒了。在 viewDidLoad 中,我尝试了完全相同的日志,它正在返回(null)。我认为这意味着它没有正确保存中心。我是否在这里遗漏了一些基本的东西,因为我在应用程序的其他地方使用了 NSUserDefaults 并且它一直工作正常。非常感谢。
编辑:这是尝试帮助调试的整个代码:)

-(void)getBounds
{
lowerBoundX = 250;
upperBoundX = 310;
lowerBoundY = 290;
upperBoundY = 350;

}

#pragma mark -
#pragma mark UIPanGestureRecognizer selector

- (void) dragGesture:(UIPanGestureRecognizer *) panGesture
{
[self getBounds];

CGPoint translation = [panGesture translationInView:self.view];

switch (panGesture.state) {
case UIGestureRecognizerStateBegan:{
originalCentre = dragImage.center;
}
break;
case UIGestureRecognizerStateChanged:{
dragImage.center = CGPointMake(dragImage.center.x + translation.x,
dragImage.center.y + translation.y);

}
break;
case UIGestureRecognizerStateEnded:{
if (((dragImage.center.x >= lowerBoundX) && (dragImage.center.y >= lowerBoundY) &&
(dragImage.center.x <= upperBoundX) && (dragImage.center.y <= upperBoundY))) {

dragImage.center = CGPointMake(280, 320);
[dragImage setUserInteractionEnabled:NO];

theCentre = [NSUserDefaults standardUserDefaults];

NSString *centre = NSStringFromCGPoint(dragImage.center);

[theCentre setObject:centre forKey:@"centre"];

NSLog(@"%@", [theCentre objectForKey:@"centre"]);
[theCentre synchronize];

break;
}
[UIView animateWithDuration:0.5
animations:^{
dragImage.center = originalCentre;
}
completion:^(BOOL finished){
}];
}
break;
default:
break;
}

[panGesture setTranslation:CGPointZero inView:self.view];
}

-(IBAction)clear{
[UIImageView animateWithDuration:0.5 animations:^{
dragImage.center = CGPointMake(100, 200);
}];

[dragImage setUserInteractionEnabled:YES];
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.

NSLog(@"%@", [theCentre objectForKey:@"centre"]);

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragGesture:)];

[dragImage addGestureRecognizer:panGesture];

[dragImage setUserInteractionEnabled:YES];

}

最佳答案

数据保存在 NSUserDefaults首先被缓存,因此它不能立即从 NSUserDefaults 的其他实例中使用。数据会按照某些预定义的事件/时间间隔定期保存。但是您可以通过调用 synchronize 来强制数据同步。像这样:

NSString *theCenter = NSStringFromCGPoint(image.center);
theCenter = [NSUserDefaults standardUserDefaults];
[theCenter setObject:centre forKey:@"center"];
[theCenter synchronize];

关于cocoa - 使用 NSUserDefaults 存储图像坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10486190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com