i'm in a bit of a situation here...
i am passing a string to a function and in that function i need to create an array whose name is the value of the string.
Say, for example: -(void) function : (NSString *) arrayName; //let arrayName = #"foo";
In this function I need to create an array named "foo" i.e the value of the passed parameter.
Can anyone help please :|
Thanks in advance ;)
Arrays don't have names. Variables have names, but variables are local to their scope, so once you leave the scope of that method, having a variable named "foo" is pointless; you can name the variable whatever you want and it will work just fine. Ex:
- (void) function:(id)whatever {
NSArray * myVariable = [NSArray arrayWithStuff....];
//use myVariable
}
What are you really trying to do?
That is not possible in Objective-C, but you can use e.g. a dictionary that maps a string to an array.
E.g. assuming something like the following property:
#property (readonly, retain) NSMutableDictionary *arrays;
... you can store an array by name:
- (void)function:(NSString *)arrayName {
NSArray *array = [NSArray arrayWithObjects:#"foo", #"bar", nil];
[self.arrays setObject:array forKey:arrayName];
}
... and access it like so:
NSArray *array = [self.arrays objectForKey:arrayName];
C is a compiled language where any source code names (for variables, functions, etc.) are not available at runtime (except for perhaps optionally debugging, -g). The Objective C runtime adds to this the ability to look up Obj C methods and classes by name, but not objects, nor any C stuff. So you're out of luck unless you build your own mini-language-interpreter structure for reference-by-name. Lots of ways to do this, but simple languages usually build some sort of variable table, something like a dictionary, array, or linked-list of objects (structs, tuples, etc.) containing string name, object pointer (maybe also type, size, etc.).
Related
I have an Array comprised of further sub-Arrays
I want to display a summary of the contents of the sub-arrays into a TableView with the count of occurrences of each entry. I have determined that the best and easiest way is through a NSMutableDictionary as an intermediate step.
I declare the dictionary in my implementation
#implementation ReviewViewController
{
NSMutableDictionary *dict;
}
and down in my methods I initialise and use it like so:
dict = [NSMutableDictionary new];
[dict setObject:[Observation entryCount] forKey:[observedItem species]];
The swapping of key and object is deliberate as its the count I want. I'm using the fact that values are retained, but keys are overwritten, so if i swap them round i get the curation for free.
It works!, but every time the method is invoked, the Dictionary is clobbered by the re-initalization so I only get the last thing entered. Anywhere else and it falls out of scope.
if I pass it as an arguement in the method name instead, I get the message "Local declaration of 'dict' hides instance variable ". The code is already an irreducable set of parts, so
so, where is the correct place for the instantiation?
I'd love to make my contribution here as a meaningful thanks, but before I can do that I'm going to look silly with such questions.
You would usually initialise it in your init method. For a view controller this is usually the following:
- (id)initWithNibName:(NSString*)nibName bundle:(NSBundle*)bundle {
if ((self = [super initWithNibName:nibName bundle:bundle])) {
dict = [NSMutableDictionary new];
}
return self;
}
I don't understand what you mean by "Anywhere else and it falls out of scope.". It's an instance variable. It is therefore in scope in any method in the class.
By the way, I would name your instance variables with an underscore prefix, e.g. _dict. This is common convention and it helps you to remember when using it that it's an instance variable.
The only way I found to passing objects between the JS and Obj-C it's by encoding the JS object by using JSON.stringify() and pass the json string to PhoneGap.exec
PhoneGap.exec('Alarm.update',JSON.stringify(list));
... and rebuild the object in Obj-C:
NSString *jsonStr = [arguments objectAtIndex:0];
jsonStr = [jsonStr stringByReplacingOccurrencesOfString:#"\\\"" withString:#"\""];
jsonStr = [NSString stringWithFormat:#"[%#]",jsonStr];
NSObject *arg = [jsonStr JSONValue];
It's that correct ? there is a better/proper/official way for doing this ?
PhoneGap.exec was designed for simple types. Your way is ok, alternately you can just pass your single object in (would only work for a single object only, see footer about how we marshal the command), and it should be in the options dictionary for the command. Then on the Objective-C side, use key-value coding to automatically populate your custom object with the dictionary.
e.g.
MyCustomObject* blah = [MyCustomObject new];
[blah setValuesForKeysWithDictionary:options];
If you are interested in how PhoneGap.exec works, read on...
* --------- *
For PhoneGap.exec, the javascript arguments are marshaled into a URL.
For the JS command:
PhoneGap.exec('MyPlugin.command', 'foo', 'bar', 'baz', { mykey1: 'myvalue1', mykey2: 'myvalue2' });
The resulting command url is:
gap://MyPlugin.myCommand/foo/bar/baz/?mykey1=myvalue1&mykey2=myvalue2
This will be handled and converted on the Objective-C side. foo, bar, baz are put in the arguments array, and the query parameters are put in the options dictionary. It will look for a class called 'MyPlugin' and will call the selector 'myCommand' with the arguments array and options dictionary as parameters.
For further info, see phonegap.js, look at PhoneGap.run_command
I think this is the best way to do it, if not the only way.
The PhoneGap.exec call just takes a NSDictionary of objects under the covers so I don't see of a better way to handle it.
most methods are structured like
- (void)someMethod:(NSArray*)arguments withDict:(NSDictionary*)options {
}
I have dozens of NSStrimgs that when the app loads I want to all be set to the same set. All of them. How can I do this without typing out every single one? Is there a shortcut method?
Thanks.
Also the problem is that Josh isn't specific enough about how he's using his dozens of strings... I think this would be better:
NSMutableArray *stringsArray = [NSMutableArray arrayWithCapacity:1];
NSString *tempStr = #"My unique string"; // Thanks Sven!
// Say you want a dozen strings
for (int i = 0; i < 12; i ++) {
[stringsArray addObject:tempStr];
}
// Now you can use them by accessing the array
[self doSomethingWithString:[stringsArray objectAtIndex:8]];
Instead of having dozens of strings that have the same value, could you make a single static global string and reference that? If you need to change it to separate values later, use instance variables that are initialized to the global string.
This sounds like your model is not very good at all. Since you want to initialize all of your strings to the same value they are obviously related and probably should be modeled as an array like iPhoneDevProf described. That makes other things a lot easier too, you can move other code that is repeated for every string into a loop.
If the value is known when you are compiling the code AND it is not going to change after subsequent application sessions then you can use a simple #define.
#define MY_DEFAULT_STRING #"THE DEFAULT STRING"
Now all you have to do is the following.
{
NSString *myString1 = MY_DEFAULT_STRING;
NSString *myString2 = MY_DEFAULT_STRING;
....
NSString *myStringN = MY_DEFAULT_STRING;
}
If all the strings are in the same code file, just put the define at the top. If the strings are in separate code files, then it could be put into your precompiled header. Having a constants file is usually better.
Using constant extern NSString would probably be more correct, but this is simple and easy to do.
I'm attempting to create an NSArray with a grouping of string literals, however I get the compile error "Initializer element is not constant".
NSArray *currencies = [NSArray arrayWithObjects:#"Dollar", #"Euro", #"Pound", nil];
Could someone point out what I'm doing wrong, and possibly explain the error message?
New syntax for creating an array with string literals:
NSArray *currencies = #[#"Dollar", #"Euro", #"Pound"];
To fix your complication error the code must be in a method. If you want to use it statically then create a class method that follows the singleton pattern.
This isn't a problem with the NSArray creation itself (you would get the same error if you wrote [NSArray array] instead), but with where you've written it. I'm guessing this is a global or file-static NSArray. In C, that kind of variable has to have a constant initializer — meaning not a function call (or, by extension, a method call). The solution is to put the actual creation and assignment of the array into a method that will be called before you need the array, such as initialize.
It sounds like Chuck has spotted the problem. One thing you want to be aware of though in coding your solution is that you'll want to avoid storing an autoreleased instance of NSArray in a static variable. Also, a common pattern for these situations is to write a class method that creates and returns the value stored in the static variable, like so:
+ (NSArray *)currencies
{
static NSArray *_currencies;
// This will only be true the first time the method is called...
//
if (_currencies == nil)
{
_currencies = [[NSArray alloc] initWithObjects:#"Dollar", #"Euro", #"Pound", nil];
}
return _currencies;
}
Although this is old, please notice that Apple committed a new patch to the llvm project adding support for new Objective-C literal syntax for NSArray, NSDictionary and NSNumber.
See here and here
I'm a newbie in objective-c, but I think that the correct code is:
NSArray *currencies = [[NSArray alloc] initWithObjects:#"Dollar", #"Euro", #"Pound", nil];
I am not sure tho.
There's nothing wrong with that code. Are you sure the error is being produced at that line?
I have a variable declared like this in a class:
Entity *array[BOARD_SIZE][BOARD_SIZE];
I need to set up either a #property that allows me to access (read) the array elements, or a function that returns a reference so I can access the array elements.
- ( ??? ) getEntityArray
{
return ???;
}
or
#property (????) Entity ??? ;
I really need to work with the array declared in this way.
Any advice?
Thanks!
Don't do this. Use an NSArray to store Objective-C objects.
Have a look at the answer to this question if you want to know how to handle multi-dimensional arrays of primitives:
Add 2d int array to NSDictionary
While Rob's answer is valid, the question itself is interesting. Objective C is just a layer on top of standard C, so a question about returning array types is valid.
The answer to the question is pretty easy: it's not possible to return array types in C. You can only return pointers. The problem with returning a pointer is that the dimensions of the multidimensional array are unknown to the caller, so you can't use the returned value as a multidimensional array.
You could do one of the following - use a typedef to make it easier to handle or not.
in your .h file:
#define BOARD_SIZE 32
typedef NSString *EntityArrayPtr[BOARD_SIZE][BOARD_SIZE];
#interface EntityTestWithNSString : NSObject {
EntityArrayPtr *x;
NSString *tempStrs[15][15];
}
#property NSString **tempStrs;
#end
in your .m file:
- ( EntityArrayPtr *) getEntityArray
{
return x;
}
- (NSString **) getStringArrays
{
return &tempStrs[0][0];
}
I just compiled this and it compiles. I'll leave it to you to see which works best for your situation.
You could make methods that grab you the one entity at the index1.index2 that you need...
I definitely would make methods to return to you exactly the object you need, instead of handing off an array pointer and letting some other object mess around with it.