2011-06-17 48 views
0

有没有办法将NSString的内容用作NSArray指针名称?这是可能的,这是不可用,但也许有另一种方法是这样的:使用NSString内容作为NSArray名称

NSString*[email protected]"hi"; 
NSString*[email protected]"yo"; 

NSArray*testarray=[[NSArray alloc] initWithObjects:one, two, nil]; 

NSLog(@"actual count: %i", [testarray count]); 

NSString*[email protected]"testarray"; 
NSLog(@"test count: %i",[ --insert here to get array name from testname-- count]); 

我已经尝试了各种猜测什么,我可以在里面插入用我testname作为数组名计数操作,但没有骰子。我知道这有点奇怪,但我可以预见很多有用的理由,我现在正在另一个应用中。

回答

1
NSString*[email protected]"hi"; 
NSString*[email protected]"yo"; 

NSDictionary *testDic=[NSDictionary dictionaryWithObjectsAndKeys: 
       [NSArray arrayWithObjects:one, two, nil], 
       @"testarray" ,nil]; 

NSLog(@"actual count: %i", [testarray count]); 

NSString*[email protected]"testarray"; 
NSLog(@"test count: %i",[[testDic objectForKey:testname] count]); 
+0

我认为这样做。我会试试看。 – johnbakers

0

我不知道这是否是你所需要的,但是......

您可以通过它的名字调用方法:

NSString *methodName = @"..."; 
SEL selector = NSSelectorFromString(methodName); 
[objectRef performSelector:selector]; 

此方法可能返回参考您的阵列。它应该以这种方式工作。

+0

这是一条可行的路线,但这样很费钱:我想你会用KVC来取得一个更好的性能(因为它是为此设计的),你不觉得吗? – AliSoftware

2

您可以对此使用键值编码(请参阅Key Value Coding Programming Guide)。

不管怎么说,做这种类型的代码 - 就像你的问题一样 - 通常是一个糟糕的设计。如果你需要这样做,你应该考虑检查你的代码设计(这可能在一些罕见的情况下是唯一的方法,但至少如果你需要这样做,你应该首先检查它是唯一的解决方案)

使用KVC对于将值绑定到您的模型或特定的类似东西是非常有用的,但如果您可以避免和使用直接的ivars/@属性,通常不是首选的方法。

+0

谢谢,我会检查一下。我喜欢ZhangChn提供的解决方案。 – johnbakers