从UIView属性获取对NSObject父级的引用

时间:2014-04-29 20:58:43

标签: ios objective-c uiview nsobject

我有(NSObject) Block *my_block作为属性UIView *main_view。在ViewController上我向UIPanGestureRecognizer添加main_view,因此手势方法必须在ViewController上。是否已经有办法从手势方法中了解特定my_block的{​​{1}}所有者?

这是因为我有main_view NSMutableArrayBlock会在运行时添加到Blocks

我的第一个想法是通过NSMutableArray循环比较识别器的每个NSMutableArraymain_view。另一个想法是继承UIView并创建对其各自UIView的引用。但也许有一种更清洁的方法。

这是我的类和方法的一个简单示例。

Block.h

Block

ViewController.m

#import <Foundation/Foundation.h>

@interface Block : NSObject

@property (nonatomic, strong) UIView *main_view;

@end

3 个答案:

答案 0 :(得分:1)

您的Block课程是否为您的手势识别器的target

<强> Block.h

@interface Block : NSObject

@property (nonatomic, strong) UIView *main_view;

@end

<强> Block.m

@implementation Block

-(void)handleMainViewPan:(UIPanGestureRecognizer *)recognizer
{
    // Now recognizer.view is the same view as self.main_view
    // Use self as this is now your block
}

@end

<强> ViewController.m

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // the Blocks are actually added on runtime to a NSMutableArray, but this is a simpler example

    Block *my_block = [[Block alloc] init];
    UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:my_block action:@selector(handleMainViewPan:)];
    [my_block.main_view addGestureRecognizer:gestureRecognizer];
    [self.view addSubview:my_block.main_view];
}

@end

答案 1 :(得分:0)

您也可以使用函数来代替子类化UIView:

void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
id objc_getAssociatedObject(id object, const void *key)

来自docs

  

使用给定的键和设置给定对象的关联值   协会政策。

好文章http://nshipster.com/associated-objects/

答案 2 :(得分:0)

如果您已在数组中包含(我相信该数组是ViewController中的属性),您可以找到loop的一个块。

示例:

// self.blocks is NSMutableArray where blocks are stored

- (void)handlePan:(UIPanGestureRecognizer *)recognizer
{
    Block *owner = nil;
    for (block in self.blocks) {
        if (block.main_view == recognizer.view) {
            owner = block;
            break;
        }
    }
}