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 {
}
Related
i would like to know that after passing object from view to view with URL, how to i pass it to the model
so i can use it for web service and populate the datasource.
Using Three20 (:
Thanks.
Copied from: http://three20.info/article/2010-10-06-URL-Based-Navigation
Original Author: Jeff Verkoeyen
One of the first questions people ask about TTNavigator is how to pass native objects around, rather than encoding them somehow in a URL. There is a simple pattern for this, using the query property of TTURLAction (or its equivalent convenience function, applyQuery:). For example, imagine you wanted to pass along an NSArray of items to show in the new view:
NSArray *arr = [...load up with data...];
[[TTNavigator navigator] openURLAction:[[TTURLAction actionWithURLPath:#"tt://restaurant/Chotchkie's"]
applyQuery:[NSDictionary dictionaryWithObject:arr forKey:#"arrayData"]]];
In this example, the array is passed directly to the initWithName: but only if there is a matching selector that accepts the query:
-(id) initWithName: (NSString*)name query:(NSDictionary*)query {
for (MyObject* item in [query objectForKey:#"arrayData"])
//... do something with item ...
}
// ...
}
This is my code:
NSString *newString = #"new value";
[breakdownCollection objectAtIndex:i] = newString;
breakdownCollection is an NSArray of multiple strings. I need to access a given string contained in the array via index number, and change the string's content to that of the new string. Note that I cannot simply replace the string with the new one, I am only trying to replace its contents.
When I try to do this, however, I get an "lvalue required as left operand of assignment" error.
Any help with this issue would be very much appreciated!
The error you get is because you wrote the assignement instruction incorrectly. That is, you cannot assign newString to [breakdownCollection objectAtIndex:i].
Also, you won't be able to do it this way. Instead, in order to modify string object content, use NSMutableString, which provides methods to do so (NSString are immutable objects).
So, for example you should try :
[[breakdownCollection objectAtIndex:i] setString:newString];
assuming you put NSMutableString into breakdownCollection.
PS : in order to change the object at the index i, you have to use NSMutableArray instead of NSArray, and then call :
[breakdownCollection replaceObjectAtIndex:i withObject:newString];
Good luck !
NSMutableString class reference
NSMutableArray class reference
Use an NSMutableArray instead and then you can use the method -replaceObjectAtIndex: withObject:
I sometimes like to organize IB elements into NSArrays primarily to help me organize my elements. Most often, different classes of objects make it into the same array with each other. While this is a convenient way of organization, I can't seem to wrap my head around why if I have an array like this:
NSArray *array = [NSArray arrayWithObjects:((UITextField *)textField), ((UISegmentedController *)segmentedController), nil];
Why I get "Does not respond to selector" messages when I put a for loop like this:
for (UITextField *text in array) {
[text setText:#""];
}
The for loop seems to be passed objects that are not of class UITextField.
What is the point of declaring the object's class if all objects in the specified array are passed through the loop?
EDIT Just for reference, this is how I'm handling it as of now:
for (id *object in array) {
if ([object isMemberOfClass:[UITextField class]]) {
foo();
} else if ([object isMemberOfClass:[UISegmentedController class]) {
bar();
}
}
When you do
for (UITextField *text in...
the object pointers from the array are cast to UITextField* type - so if the object isn't actually a UITextField, all sorts of weird things may happen if you try to call UITextField methods.
So instead use the id type (no * needed, btw):
for (id obj in array)
Then check the type as you do and call the appropriate methods. Or, filter the array to get only objects of a certain type, then go though that type only:
for (UITextField* text in [array filteredArrayUsingPredicate:...])
Edit: here's how to build class filter predicates:
Is it possible to filter an NSArray by class?
What is the point of declaring the object's class if all objects in the specified array are passed through the loop?
The class name is just there to let the compiler know what it should expect to find. This allows it to try to figure out what methods it should expect you to call and how you might treat the object. It's the same idea as passing in an int to a method that takes float. The method will not ignore ints - it's assuming you're passing the correct type. You're just giving this construct a little more credit than it's due:
for (UITextField *text in array)
It just doesn't have that functionality. How you're handling it now is the correct way.
Are you sure you don't get an error when you run that code? The "does not respond to selector" message is a runtime error, not a compile time error. The compiler has no idea whether the objects in the array implement -setText:, but you should certainly get an error when you actually send that message to an instance of UISegmentedControl.
Another possibility is that you've got a class called UISegmentedController that does have a -setText: method. The name of the class that implements the multi-part bar-graph-looking user interface widget is UISegmentedControl. So either the code you're showing isn't real, tested code, or you've got a class that we don't know about.
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.).
I have a class that I use to setup objects in an array. In this class I have a custom "initWithDictionary", where I parse a JSON dictionary. However, as I am running into NSNull, this crashes my app. To get around this, I set up a class that handles exceptions, so when a string is NSNull, it's replace it with #"". or -1 for integers.
This is my NullExtensions class:
#interface NSNull (valueExtensions)
-(int)intValue;
-(NSString *)stringValue;
#end
#implementation NSNull (valueExtensions)
-(int)intValue {
return -1;
}
-(NSString*)stringValue {
return #"";
}
#end
However, in my initWithDictionary method, the following code crashes my app:
self.bookTitle = [[parsedDictionary objectForKey:#"book_title"] stringValue];
It doesn't work regardless of the object in the parsed dictionary being NSNull or containing a valid string. Only if I do the following (and the string is not null):
self.bookTitle = [parsedDictionary objectForKey:#"book_title"];
Is stringValue incorrect in this case? And if so, how do I use it properly in order to setup proper NSNull replacements?
Thx
You really really don't want to add a category to NSNull that adds such common methods. That will change the behavior of NSNull for all instances in the application, including ones created by the underlying frameworks solely for their private use.
If you need a value class that represents the notion of "value doesn't exist and therefore I'm going to return these default values instead", create a class or instance that represents exactly that.
As for why it crashes, I couldn't tell you without seeing the actual details of the crash.
And, yes, it really is THAT bad to add a category to a class that adds such a common method. All it takes is one bit of code in a plug-in or framework that does:
if ([fooMaybeNull respondsToSelector: #selector(intValue)] bar = [fooMaybeNull intValue];
Not terribly farfetched -- I have had to debug nasty crashers or misbehaviors due to exactly this kind of willy-nilly category addition.
If you are going to add methods to a class via categories, prefix your method names so as to isolate them from existing functionality. It is still fragile, but manageably so.
Instead of creating categories on NSNull, for which you would also have to add a similar category to NSString (that's why it crashes, because real strings do not respond to stringValue) - instead try creating a helper category on NSDictionary like "stringForKey" that uses the code Johan posted and returns an NSString, probably also should enforce all other types get mapped to empty strings as well.
The NSNull extensions you have written look ok to me but using a method like stringValue may be confusing since other classes like NSNumber use this.
Personally though, I think NSNull replacement in this instance is unnecessary. If you just made a quick test you can replace the NSNull where you need to. e.g.
id testObject = [parsedDictionary objectForKey:#"book_title"];
self.bookTitle = testObject==[NSNull null] ? #"" : testObject;
You are asking an NSString for its stringValue. No need to convert a string to a string.
Try this:
if (![[parsedDictionary objectForKey:#"book_title"] isKindOfClass:[NSNull class]]) {
self.bookTitle = [parsedDictionary objectForKey:#"book_title"];
} else {
self.bookTitle = #"";
}
Edit: You should not use the category on NSNull you created. You don't need it, nor should you want it. If the source for the dictionary inserts NSNull instances, go ahead and use my code above. Normally you would expect to simple have no value inserted for the key, at which time you can simple see if [parsedDictionary objectForKey:#"book_title"] returns anything.
Are you sure that the dictionary is returning [NSNull null]? By default, dictionaries return nil, not [NSNull null], when an value isn't found for a key.
However, in my initWithDictionary method, the following code crashes my app:
self.bookTitle = [[parsedDictionary objectForKey:#"book_title"] stringValue];
It doesn't work regardless of the object in the parsed dictionary being NSNull or containing a valid string.
That makes sense, since stringValue is not a valid method on NSString. It will work for NSValue and its subclasses, but not NSString.