問題描述
是否可以用一個字符串和一個int來引用一個變量,像這樣:
Is it possible to reference a variable with a string and an int, like this:
int number1;
int j = 1;
@"number%i", j = 3; //Hope this makes sense..
上面的代碼給了我警告并且不起作用,怎么可能呢.
The code above gives me warnings and does not work, how could this be done.
我也試過這個,但它不起作用(原因很明顯):
I also tried this, but it doesnt work (for quite obvious reasons):
int j = 1;
NSString *refString = [NSString stringWithFormat:@"number%i", j];
refString = 3;
我真的很掙扎,我知道如何在 Javascript 中做到這一點,但在 Obj-C 中卻不知道,這可能嗎?
Im really struggling with this, I know how to do it in Javascript, but not in Obj-C, is it possible?
推薦答案
這是一個反模式 我稱之為窮人陣列.更好的方法是使用像數組這樣的適當集合,而不是使用一堆秘密相關的變量.如果做得好,帶有數組的代碼通常也會更短更簡潔.
This is an anti-pattern I call the Poor Man's Array. The better way to do this is to use a proper collection like an array instead of a bunch of variables that are secretly related. Done right, the code with an array will usually be a lot shorter and cleaner too.
這篇關于是否可以使用字符串和 int 引用變量?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!