【问题标题】:How to access a class instance from another method如何从另一个方法访问类实例
【发布时间】:2012-12-18 09:05:33
【问题描述】:

这是我的代码:

#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”。

提前致谢!

【问题讨论】:

  • rect1保存为实例变量。
  • 这与您的问题无关,但它在 Objective C 中的标准是以大写字母开头的类名(即 TempViewController 和 MyRect)。这使得区分对象和类变得更加容易。
  • 好的,谢谢!会做。现在谁给了我的问题一个负1....大声笑

标签: objective-c class methods instance


【解决方案1】:

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

#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;
    }
}

【讨论】:

  • @synthesize 在当前编译器中不是必需的——它是自动生成的。声明为 readonly 的属性除外。
  • 谢谢!对了,rect1属性前面应该有一颗星星吧?
  • @nielsbot 我使用@synthesize,所以我可以在setter 和getter 方法中访问_propertyName 变量。它使自定义这些方法变得更加容易。
  • 不,没有明星。 CCRect 不是一个对象,而是一个 c 结构体。
  • 而且您确实不需要在现代编译器中综合任何属性。这是隐式完成的。
【解决方案2】:

您可以通过将rect1 放置在您的.h 文件中来将其设为实例变量。您可以执行以下操作:

@interface tempViewController : UIViewController
{
      myRect *rect1;
}

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

【讨论】:

  • 直接在标头中声明 ivar 不是当前的做法—— ivar 几乎总是应该通过声明的属性来处理。
  • 或至少在 @implementation 中声明它,因为现代版本的 clang 允许您这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 2016-01-15
  • 2014-11-05
  • 2020-03-19
  • 1970-01-01
相关资源
最近更新 更多