概述:我有一个MapKit地图、一个PickerView和一个武器对象的静态数组(每个武器都有一些成员变量数据(。目的是使用picker视图并在地图上显示一些信息(范围、名称(。
需要一些关于存储在我的Singleton中的对象数组的帮助。我成功地将数组传递到了映射中,但选择器显示的是对象的内存位置,而不是名称。
在SingletonFile.m中创建对象数组
static dispatch_once_t pred;
static SingletonFile *shared = nil;
dispatch_once(&pred, ^{
shared = [[SingletonFile alloc] init];
shared.theWeapons = [NSMutableArray arrayWithArray:
@[[[weapon alloc] initWithName:@"M16" weaponPicName:@"M16 Pic Name"],
[[weapon alloc] initWithName:@"M20" weaponPicName:@"M20 Pic Name"],
[[weapon alloc] initWithName:@"M3" weaponPicName:@"MyName"]
]];
//This is my attempt to create a second array with only the weaponPicName's from theWeapons array created above.
shared.theWeaponNameArray = [shared.theWeapons valueForKey:@"weaponPicName"];
//This line produces the error, not key value coding-compliant for the key weaponName
//weaponName and weaponPicName are a part of the weapon object
});
return shared;
武器对象的Weapon.m构造函数
-(id)initWithName:(NSString*)weaponName weaponPicName:(NSString*)weaponPicName {
self = [super init];
if (self) {
_weaponName = weaponName;
_weaponPicName = weaponPicName;
}
return self;
}
MapViewController.m是我从我的单例类中获取武器数组的地方
//Initialize tableNames to the singleton name array for use in picker
self.tableNames = [SingletonFile weaponSingleton].theWeapons;
MapViewController.m(下面(是我的picker代码。
- (IBAction) pickType:(id)sender {
arrayPickerRows = self.tableNames;
[ActionSheetStringPicker showPickerWithTitle:@"Select"
rows:arrayPickerRows
initialSelection:0
doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
selectedRow = [arrayPickerRows objectAtIndex:selectedIndex];
[self typePickerDone:sender];
}
cancelBlock:^(ActionSheetStringPicker *picker) {
NSLog(@"Block Picker Canceled");
}
origin:sender];
}
- (void) typePickerDone:(UIButton*) sender {
[self.WeaponPickerbutton setTitle:selectedRow forState:UIControlStateNormal];
}
我确信答案与访问对象的weaponName有关。我曾尝试使用valueForKey从对象数组中创建一个weaponNames数组,但它说我的键不符合值。
(也知道我可以用.plist完成所有这些,但我正在努力学习Singleton并使用对象数组(
您的arrayPickerRows
存储一系列武器。当你为按钮设置标题时,所以当你使用[arrayPickerRows objectAtIndex:selectedIndex]
时,你会得到索引为selectedIndex
的武器地址。
在您的代码中,您没有变量selectedRow
的定义。但是,它应该属于weapon
类。设置按钮名称时,应使用以下代码:
[self.WeaponPickerbutton setTitle:selectedRow.weaponName forState:UIControlStateNormal];