I am not a Cocoa developer, but I have been dabbling in it to build some plugins for PhoneGap. This particular plugin method is either 1) crashing the app without saying why or 2) complaining about how I release/don't release an object. I have tried a ton of things on my end, including using an Enumerator instead of the for loop. If anyone can point me in the right direction, that would be awesome. I don't mind legwork:
- (void)getPreferences:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options {
NSUInteger argc = [arguments count];
NSString* jsCallback = nil;
if (argc > 0) {
jsCallback = [arguments objectAtIndex:0];
} else {
NSLog(@"Preferences.getPreferences: Missing 1st parameter.");
return;
}
NSDictionary *defaults = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
NSMutableArray *keys = (NSMutableArray *) [options objectForKey:@"keys"];
NSMutableDictionary *values = [[NSMutableDictionary alloc] init];
NSUInteger ky = [keys count];
for (int i = 0; i < ky; i ++) {
@try {
[values setObject:[defaults objectForKey:[keys objectAtIndex:i]] forKey:[keys objectAtIndex:i]];
}
@catch (NSException * err) {
NSLog(@"Error %@", err);
}
}
[keys release];
NSString* jsString = [[NSString alloc] initWithFormat:@"%@(%@);", jsCallback, [values JSONRepresentation]];
[defaults release];
[values release];
[webView stringByEvaluatingJavaScriptFromString:jsString];
[jsString release];
}
Human version:
options
contains a dictionary with a single key of "keys"- that key contains an array of strings (that are going to be used as keys for lookup)
- I want to loop through that array and
- For every value that exists in
defaults
for that key, copy it tovalues
using the same key - Finally, I want to send that
value开发者_运维技巧s
back as JSON (This part was working when I just passed the entiredefaults
object in, so I think the JSON method is working)
From your code, it follows that you 'own' objects values
and jsString
(the ones you created with alloc
), so you should release them and not any other.
You can read more on memory management here.
Is this the whole code? Also, what exactly error do you get?
Nikita is right, it looks as though you're overreleasing defaults
, which would cause a crash later when the autorelease pool gets released. Also, if I understand what you're trying to do correctly, you could create the values
dictionary with a single line of code:
NSDictionary *values = [defaultsDict dictionaryWithValuesForKeys:keys];
精彩评论