我正在修改一个早期项目,其中使用标签来识别 1-of-5、1-of-16 或 1-of-10UIButtons
。我想根据我的理解用自定义属性替换标签这个答案 https://stackoverflow.com/a/11594662/2348597.
该属性称为myInfo
由一个字符串和一个整数组成。这很可能是另一个名称的标签,但它使消息源能够以简单整数标签所不能的方式唯一地识别,从而从我的代码中清除幻数,并有望改进文档。
该属性是使用类别创建的
UIView+自定义属性.m
#import "UIView+CustomProperties.h"
@implementation UIView (MyInfo)
-(void)setMyInfo:(id)info
{
objc_setAssociatedObject(self, "_myInfo", info, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(id)myInfo
{
return objc_getAssociatedObject(self, "_myInfo") ;
}
@end
And myInfo
当我导入时有效objc/runtime.h
UIView+自定义属性。
#import <objc/runtime.h>
@interface UIView (MyInfo)
@property ( nonatomic, strong ) id myInfo;
@end
我从方法中调用类别(below)在 UIView 中我创建了几组按钮。
// define type and number of 5, 16 or 10 buttons
switch (buttonCount) {
case 5:
roundButton.myInfo = [NSString stringWithFormat:@"transpose index %i", i ];
break;
case 16:
roundButton.myInfo = [NSString stringWithFormat:@"player index %i", i ];
break;
case 10:
roundButton.myInfo = [NSString stringWithFormat:@"note index %i", i ];
break;
default:
roundButton.myInfo = @“orphan button“;
break;
}
为了识别消息源,我尝试删除所有非数字字符myInfo
using 这个方法 https://stackoverflow.com/a/1426819/2348597。但是我的选择器方法出现问题forButtons
当我尝试删除非数字字符时
- (void)fromButtons:(UIButton*)button {
NSLog(@"Button %ld tapped", (long int)[button tag]);
NSLog(@"first, %@", button.myInfo);
NSString *newString = [[button.myInfo componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:@""];
NSLog(@"then, %@", newString);
NSLog(@"and %li", (long int)newString);
当我构建并运行并按下按钮 1 时,NSLog
上面的语句产生以下日志
2017-05-25 18:27:33.147 SatGam3[930:607301] Button 1 tapped
2017-05-25 18:27:33.147 SatGam3[930:607301] first, transpose index 1
2017-05-25 18:27:33.148 SatGam3[930:607301] then, 1
2017-05-25 18:27:33.148 SatGam3[930:607301] and 2070247168
请注意,long int
原始标签的值是正确的,即 1,而long int
从定制属性中恢复的值为 2070247168。
Q.1 首先,这种做法正确吗?
Q.2 如果是这样,有人可以解释一下为什么我要从中提取 9 位数字值吗?myInfo
?