你好,我有一个问题。我希望任何人都能帮助我。我有一个方法returnPointFromArray,我有一个数组的值(例如50.0,100.0)。然后我想随机它,然后我想在方法drawObjectWithPoint中使用CGPoint p来定位我的对象(来自另一个类的对象)的随机值。
但是drawObjectWithPoint方法总是说CGPoint p为0.0,0,0,或者他说"使用未声明的标识符p
或"实例变量隐藏…"。
我尝试了同样的原理来测试int,这是有效的。
我不知道我做错了什么。
如果有人能帮我解释一下我做错了什么,那就太好了。谢谢你。
.h
-(void)returnPointFromArray;
-(void)drawObjectWithPoint;
.m
-(void)returnPointFromArray
{
NSArray *points = [];
//Random for points
NSUInteger *randomIndex = arc4random() % [points count];
NSValue *val = [points objectAtIndex:randomIndex];
CGPoint p = [val CGPointValue];
}
-(void)drawObjectWithPoint
{
Object *myObject [[Object alloc]init];
CGPoint pNew = p;
myObject.position =
[self addChild:myObject];
}
你可以这样做:编辑:(这是你在。h文件中的声明方式)
#import <UIKit/UIKit.h>
@interface MyClass : UIViewController {
CGPoint p;
}
-(void)returnPointFromArray;
-(void)drawObjectWithPoint;
@end
in .m file
-(void)returnPointFromArray {
NSArray *points = [];
//Random for points
NSUInteger *randomIndex = arc4random() % [points count];
NSValue *val = [points objectAtIndex:randomIndex];
p = [val CGPointValue]; // change here
}
-(void)drawObjectWithPoint {
Object *myObject [[Object alloc]init];
CGPoint pNew = p;
myObject.position =
[self addChild:myObject];
}
直接通过方法调用赋值
-(void)drawObjectWithPoint
{
Object *myObject [[Object alloc]init];
myObject.position = [self returnPointFromArray];
[self addChild:myObject];
}
-(CGPoint)returnPointFromArray {
NSArray *points = [];
//Random for points
NSUInteger *randomIndex = arc4random() % [points count];
NSValue *val = [points objectAtIndex:randomIndex];
return [val CGPointValue];
}
刚刚在。h文件中声明了CGPoint p;
。您将其声明为局部(returnPointFromArray
函数)意味着它的作用域仅为该函数的局部。检查在这里供参考。
你的returnPointFromArray方法返回void -只需修改它-
-(CGPoint)returnPointFromArray
{
// your code
return p;
}
在需要使用p的地方,只需写
CGPoint pNew = [self returnPointFromArray];
显然你必须添加代码来实际使用这个值-你的代码根本不会这样做-
myObject.position = pNew;