如何从另一个方法访问类实例

时间:2013-01-03 22:42:53

标签: objective-c class methods instance

这是我的代码:

#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad
{
  [super viewDidLoad];

  UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(50.0, 50.0, 0, 0)];
  [self.view addSubview:view1];
}


-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    if([touch.view isEqual:self]) {
        CGPoint point = [[touches anyObject] locationInView:self];
        NSLog(@"%@",NSStringFromCGPoint(point));
        self.view1.center = point;
     }
}

我希望能够从touchesMoved方法访问“UIView”类的实例“view1”。

提前致谢!

2 个答案:

答案 0 :(得分:2)

您可以按照另一个答案中的说明声明局部变量。但是,在我看来,最好在匿名类别中声明私有属性,如下所示:

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UIView *view1; // declares view1 as a private property
@end

@implementation ViewController 
@synthesize view1 = _view1;

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view1 = [[UIView alloc] initWithFrame:CGRectMake(50.0, 50.0, 0, 0)];
    [self.view addSubview:self.view1];
}


-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    if([touch.view isEqual:self])
    {
        CGPoint point = [[touches anyObject] locationInView:self];
        NSLog(@"%@",NSStringFromCGPoint(point));
        self.view1.center = point;
    }
}

答案 1 :(得分:0)

您可以将rect1实例变量放入.h文件中。你可以这样做:

@interface tempViewController : UIViewController
{
      myRect *rect1;
}

然后在.m文件中,您不必再次声明它。