有没有办法在objective-c中转换对象,就像在VB.NET中转换对象的方式一样?
例如,我正在尝试执行以下操作:
// create the view controller for the selected item
FieldEditViewController *myEditController;
switch (selectedItemTypeID) {
case 3:
myEditController = [[SelectionListViewController alloc] init];
myEditController.list = listOfItems;
break;
case 4:
// set myEditController to a diff view controller
break;
}
// load the view
[self.navigationController pushViewController:myEditController animated:YES];
[myEditController release];
Run Code Online (Sandbox Code Playgroud)
但是我收到编译器错误,因为'list'属性存在于SelectionListViewController类中,但不存在于FieldEditViewController上,即使SelectionListViewController继承自FieldEditViewController.
这是有道理的,但有没有办法将myEditController转换为SelectionListViewController,以便我可以访问'list'属性?
例如在VB.NET中,我会这样做:
CType(myEditController, SelectionListViewController).list = listOfItems
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助!
我可以创建一个所有元素都是类型的NSMutableArray实例吗?SomeClass
generics collections objective-c strong-typing data-structures
所以,显然,在WWDC之后,我正在玩上周提出的新内容.如您所知,Apple在Objective-C世界中引入了泛型
注意:这个答案以某种方式跟进了这个问题: Objective-C中是否存在强类型集合?
我在方法中尝试了这个代码,效果很好
NSMutableArray<NSString*> *array = [[NSMutableArray alloc] init];
[array addObject:@""];
[array addObject:@(54)];Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString * __nonnull'
// Great, generics works as expected.
Run Code Online (Sandbox Code Playgroud)
但是我也有想要转换为泛型的方法
在头文件中:
- (NSArray <NSString*> *)objectsToSearch;
Run Code Online (Sandbox Code Playgroud)
执行:
- (NSArray <NSString*> *)objectsToSearch
{
NSString *first = @"1";
NSString *second = @"2";
NSString *third = @"3";
NSNumber *test = @(55);
return @[first, second, third, test]; // No-error!!!
}
Run Code Online (Sandbox Code Playgroud)
我做错了什么或Clang不支持泛型+文字或者还有其他我缺少的东西?