编辑:我为浪费时间道歉,错误与我正在做的事情无关,而是我的代码中的一些逻辑让我相信这是原因。自从使用他的想法通过整个 AuthorSelectionView 以及他关于更正 NSNumer 错误的说明以来,我授予 Kevin 正确答案。对于那个很抱歉。
我已经想了好几个小时,甚至搁置了一天,仍然无法弄清楚......
我的情况如下:
我创建了一个实现“UIView”的自定义类,并将这个类变成了一个协议,如下所示:
自定义 UIView h 文件
@protocol AuthorSelectionViewDelegate <NSObject>
-(void)AuthorSelected:(NSNumber *)sender;
@end
#import <UIKit/UIKit.h>
@interface AuthorSelectionView : UIView
@property (nonatomic,assign) id<AuthorSelectionViewDelegate> delegate;
@property (strong,retain) NSNumber *authorID;
- (id)initWithFrame:(CGRect)frame withImage:(UIImage *)img withLabel:(NSString *)lbl withID:(int)authorID ;
@end
实施...
- (id)initWithFrame:(CGRect)frame withImage:(UIImage *)img withLabel:(NSString *)lbl withID:(int)authorID
{
self = [super initWithFrame:frame];
if (self) {
self.authorID = [[NSNumber alloc] initWithInt:authorID]; //used to distinguish multiple instances of this class in a view.
...
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, FRAMEWIDTH, FRAMEHEIGHT)];
[button addTarget:self action:@selector(CUSTOMBUTTONCLICK) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
}
return self;
}
- (void) CUSTOMBUTTONCLICK
{
[self.delegate performSelector:@selector(AuthorSelected:) withObject:self.authorID];
}
现在我的委托对象中的方法被调用得很好,但我的主要问题是当我有多个 AuthorSelected 类的实例时,正在传递的对象发生了什么事alloc'd ..(NSNumber authorID)。我对它有一些奇怪的行为。传递的值似乎几乎是随机的,但我正在检测某种模式,其中传递的值迟到了..
这很令人困惑,所以我试着解释一下:我创建了 AuthorSelected 视图的两个实例,一个带有 authorID=1,另一个带有 authorID=2。
在第一次按下时,假设我按下第一个按钮,我会按预期得到 1。
在第二次按下时,如果我按下第一个自定义按钮,我会得到“1”,但如果我按下第二次,我仍然会得到 1。
第三次,任何一个按钮都会返回“2”
我觉得这是指针的一些问题,因为这对我来说一直是一个弱点,但是任何帮助将不胜感激,因为我似乎无法弄清楚这一点。
谢谢!
编辑:
as requested here is how I create the AuthorSelectionView Objects...
AuthorSelectionView * asView01 = [[AuthorSelectionView alloc]
initWithFrame:CGRectMake(0, 0, FRAMEWIDTH, FRAMEHEIGHT)
withImage:userPic1
withLabel:randomUserName
withID:1];
asView01.delegate = self;
AuthorSelectionView * asView02 = [[AuthorSelectionView alloc]
initWithFrame:CGRectMake(0, 0, FRAMEWIDTH, FRAMEHEIGHT)
withImage:userPic2
withLabel:randomUserName2
withID:2];
asView02.delegate = self;
一个可能很重要的细节:
一旦我单击这些自定义视图之一,我的代码设置为(现在)调用运行上述 AuthorSelectionView alloc 代码的方法,以便我可以使用相同的布局刷新屏幕,但使用不同的 userpic/userName . 这是糟糕的设计,我知道,但现在我只想让基本功能正常工作,然后会担心重绘。我提到了这个花絮,因为我知道objective-c的“层”视图像画布上的油漆一样相互叠加,并且想到也许当我点击我认为可能是我的第二个按钮时,它真的“点击”了下层并提取不正确的信息。