is my jSON well written ? i just have boxes with their detail and i want to populate a core data entity afterwards. (btw, i need a easy tutorial to set my datas in coredata, do you have? cimgf's tutorial is too complicated or i just don't understand them :/
{
"boxes": {
"boxesDetail": [
{
"codeArticle": "WPCDE01C412L",
"nameBox": "boxName",
"texteMarketing": "boxTextMarketing",
"descriptionBox": "boxDescritpion",
"nbActivities": 1650,
"kindBox": "boxKind",
"typeBox": "boxType",
"priceBox": 20,
"dlu": 2014,
"note": 3
},
{
"codeArticle": "BOOYAKA!!",
"nameBox": "boxNameName",
"texteMarketing": "boxTextMarketing",
"descriptionBox": "boxDescritpion",
"nbActivities": 1650,
"kindBox": "boxKind",
"typeBox": "boxType",
"priceBox": 39,
"dlu": 2014,
"note": 3
}
]
}
}
Just as JeremyP says, you should use a JSON Parser to check your JSON. I also fully recommend jsonlint.com for checking JSON.
As far as an easy tutorial for CoreData I would recommend Ray Wenderlich's tutorial. It's updated for iOS 5 so perhaps having an updated tutorial will help you understand. I haven't done the updated tutorial, but I'm pretty sure that's the one I looked at pre-iOS 5 when I was learning about CoreData.
After having a look at the CoreData tutorial and getting your head around it and understanding it, I would write a helper function as a category on your Box.
Something along the lines of
+ (id)boxWithDictionary:(NSDictionary *)dict withManagedObjectContext:(NSManagedObjectContext *)managedObjectContext;
{
Box *box = [NSEntityDescription insertNewObjectForEntityForName:#"Box"
inManagedObjectContext:managedObjectContext];
box.codeArticle = [dict objectForKey:#"codeArticle"];
box.nameBox = [dict objectForKey:#"nameBox"];
box.texteMarketing = [dict objectForKey:#"texteMarketing"];
box.descriptionBox = [dict objectForKey:#"descriptionBox"];
box.nbActivities = [dict objectForKey:#"nbActivities"];
box.kindBox = [dict objectForKey:#"boxKind"];
box.typeBox = [dict objectForKey:#"boxType"];
box.priceBox = [dict objectForKey:#"priceBox"];
box.dlu = [dict objectForKey:#"dlu"];
box.note = [dict objectForKey:#"note"];
return box;
}
The reason to put this code in a category and in a separate file to the Box.m and Box.h files that Xcode generate is so that if you ever edit the Box entity in CoreData and have to generate a new file, it won't overwrite this category file with your helper function.
I hope this helps.
Related
I have implement xmpp framework in my cocoa os x application. currently am working on vCard. i have done work on set all required field's data of login user and it stored successfully, but i have no proper solution for how to get login user's stored vcard and am not aware of it. Please give me solution for this problem. i have been suffering for this from last 3 days. help me as soon as
Thanx in advance
i have used below code to set vCard field
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_PRIORITY_DEFAULT);
dispatch_async(queue, ^
{
XMPPvCardCoreDataStorage *xmppvCardStorage = [XMPPvCardCoreDataStorage sharedInstance];
XMPPvCardTempModule *xmppvCardTempModule = [[XMPPvCardTempModule alloc] initWithvCardStorage:xmppvCardStorage];
[xmppvCardTempModule activate:[self xmppStream]];
XMPPvCardTemp *myvCardTemp = [xmppvCardTempModule myvCardTemp];
if (!myvCardTemp)
{
NSXMLElement *vCardXML = [NSXMLElement elementWithName:#"vCard" xmlns:#"vcard-temp"];
XMPPvCardTemp *newvCardTemp = [XMPPvCardTemp vCardTempFromElement:vCardXML];
[newvCardTemp setName:#"vCard"];
[newvCardTemp setNickname:lbl.stringValue];
[newvCardTemp setFormattedName:#"abc"];
[newvCardTemp setDesc:lbl_abt.stringValue];
[xmppvCardTempModule updateMyvCardTemp:newvCardTemp];
}
else
{
[myvCardTemp setName:#"vCard"];
[myvCardTemp setNickname:lbl.stringValue];
[myvCardTemp setFormattedName:#"abc"];
[myvCardTemp setDesc:lbl_abt.stringValue];
[xmppvCardTempModule updateMyvCardTemp:myvCardTemp];
}
});
}
And i also tried below code to retrieve vCard
/* XMPPvCardTempModule *xmppvCardTempModule;
XMPPvCardTemp *vCard =[xmppvCardTempModule vCardTempForJID:[XMPPJID jidWithString:#"xxxx"] shouldFetch:YES];
NSLog(#"V CARD :%#",vCard.nickname);*/
XMPPvCardCoreDataStorage* xmppvCardStorage = [XMPPvCardCoreDataStorage sharedInstance];
XMPPvCardTempModule* m = [[XMPPvCardTempModule alloc]initWithvCardStorage:xmppvCardStorage];
[m fetchvCardTempForJID:[XMPPJID jidWithString:#"xxxx"]ignoreStorage:YES];
NSLog(#"%#",xmppvCardStorage.description);
Please suggest me proper way to solve this problem :
OmniFocus has a Cocoa Service that allows you to create tasks based upon selected items.
It has a preference that allows you to set the keyboard shortcut that triggers the Service. This is not just a global hotkey, it's a bona fide Service that shows up in the menu.
You can the keyboard shortcut to pretty much any combination, including combinations with ⌥ and ^. This functionality is not documented - the docs seem to say that KeyEquivalents must be a ⌘+[⇧]+someKey.
Once this is set, I observe three things:
The OmniFocus Info.plist file does not contain a KeyEquivalent listed. This is not surprising, as the file is read-only.
The pbs -dump_pboard utility lists NSKeyEquivalent = {}; for the service.
Using NSDebugServices lists this interesting line that does not show up with most debugging sessions (Obviously, for keyboard shortcut ⌃⌥⌘M): OmniFocus: Send to Inbox (com.omnigroup.OmniFocus) has a custom key equivalent: <NSKeyboardShortcut: 0x7fb18a0d18f0 (⌃⌥⌘M)>.
So my questions are twofold, and I suspect they are related:
How do you dynamically change a service's KeyEquivalent?
How do you set the KeyEquivalent to a combination including ⌃ and ⌥
Thank you!
Figured it out. The basic process is described here: Register NSService with Command Alt NSKeyEquivalent
The code is this:
//Bundle identifier from Info.plist
NSString* bundleIdentifier = #"com.whatever.MyApp";
//Services -> Menu -> Menu item title from Info.plist
NSString* appServiceName = #"Launch My Service";
//Services -> Instance method name from Info.plist
NSString* methodNameForService = #"myServiceMethod";
//The key equivalent
NSString* keyEquivalent = #"#~r";
CFStringRef serviceStatusName = (CFStringRef)[NSString stringWithFormat:#"%# - %# - %#", bundleIdentifier, appServiceName, methodNameForService];
CFStringRef serviceStatusRoot = CFSTR("NSServicesStatus");
CFPropertyListRef pbsAllServices = (CFPropertyListRef) CFMakeCollectable ( CFPreferencesCopyAppValue(serviceStatusRoot, CFSTR("pbs")) );
// the user did not configure any custom services
BOOL otherServicesDefined = pbsAllServices != NULL;
BOOL ourServiceDefined = NO;
if ( otherServicesDefined ) {
ourServiceDefined = NULL != CFDictionaryGetValue((CFDictionaryRef)pbsAllServices, serviceStatusName);
}
NSUpdateDynamicServices();
NSMutableDictionary *pbsAllServicesNew = nil;
if (otherServicesDefined) {
pbsAllServicesNew = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary*)pbsAllServices];
} else {
pbsAllServicesNew = [NSMutableDictionary dictionaryWithCapacity:1];
}
NSDictionary *serviceStatus = [NSDictionary dictionaryWithObjectsAndKeys:
(id)kCFBooleanTrue, #"enabled_context_menu",
(id)kCFBooleanTrue, #"enabled_services_menu",
keyEquivalent, #"key_equivalent", nil];
[pbsAllServicesNew setObject:serviceStatus forKey:(NSString*)serviceStatusName];
CFPreferencesSetAppValue (
serviceStatusRoot,
(CFPropertyListRef) pbsAllServicesNew,
CFSTR("pbs"));
Boolean result = CFPreferencesAppSynchronize(CFSTR("pbs"));
if (result) {
NSUpdateDynamicServices();
NSLog(#"successfully installed our alt-command-r service");
} else {
NSLog(#"couldn't install our alt-command-r service");
}
If the code succeeds, you can view this in ~/Library/Preferences/pbs.plist
You should see something like:
NSServicesStatus = {
"com.whatever.MyApp - Launch My Service - myServiceMethod" = {
enabled_context_menu = :true;
enabled_services_menu = :true;
key_equivalent = "#~r";
};
That's an example
{
"updated":1350213484,
"id":"http://www.google.com/reader/api/0/feed-finder?q\u003dProva\u0026output\u003djson",
"title":"Risultati di feed per \"Prova\"",
"self":[
{
"href":"http://www.google.com/reader/api/0/feed-finder?q\u003dProva\u0026output\u003djson"
}
],
"items":[
{
"title":"Home Page - La prova del cuoco",
"id":"http://www.laprovadelcuoco.rai.it/",
"updated":1350213485,
"feed":[
{
"href":"http://www.laprovadelcuoco.rai.it/dl/portali/site/page/Page-ffb545b4-9e72-41e5-866f-a465588c43fa-rss.html"
}
],
"alternate":[
{
"href":"http://www.laprovadelcuoco.rai.it/",
"type":"text/html"
}
],
"content":{
"direction":"ltr",
"content":"Diventa un cuoco provetto con “La Prova del Cuoco”: le videoricette in un' applicazione di facile e veloce consultazione per il tuo Iphone. Scopri come acquistare ..."
}
},
{
"title":"Le prove Invalsi di matematica e italiano",
"id":"http://online.scuola.zanichelli.it/quartaprova/",
"updated":1350213486,
"feed":[
{
"href":"http://online.scuola.zanichelli.it/quartaprova/feed/"
}
],
"alternate":[
{
"href":"http://online.scuola.zanichelli.it/quartaprova/",
"type":"text/html"
}
],
"content":{
"direction":"ltr",
"content":"Un sito Zanichelli dedicato alle prove Invalsi di italiano e matematica: esercitazioni, consigli, informazioni utili, novità, aggiornamenti e blog d'autore sulle prove ..."
}
},
How can I get the feed URL?
That's what I do
NSString *daParsare=[reader searchFeed:searchText];
NSArray *items = [[daParsare JSONValue] objectForKey:#"items"];
for (NSDictionary *item in items) {
NSString *title = [item objectForKey:#"title"];
NSString *feed = [item valueForKeyPath:#"feed.href"];
}
[tab reloadData];
With the title everything is ok but when I try to access to the feed paramater I get the error...
Assuming your JSON object is named jsonObject, you would simply access the href element. So, in your current object, the URL is in an object named href, which is the first (and in this case, only) element in an array named feed at the top level:
NSString* urlString = jsonObject[#"feed"][0][#"href"];
You should check to make sure that if feed exists, it's not an empty array before you access one of its elements.
NSString *feed = [item valueForKeyPath:#"feed.href"];
is wrong, as feed refers to an array, that again holds a dictionary.
NSString *feed = [[[item objectForKey:#"feed"] objectAtIndex:0] objectForKey:#"href"];
If you are using an modern Xcode, this last line is the same as in Jason Cocos answer.
NSString* feed = item[#"feed"][0][#"href"];
this syntax is called Object Subscription.
I am trying to count the words in Pages document (the doc format is RTF) using the scripting bridge. (I can do it using NSApplescript but I would rather not have all the applescript-aware duct tape in my code)
When I perform this task using applescript (and NSAppleScript APIs) I can do this very simply (and successfully):
on wordCount(appName,docName)
local mydoc
local wordcount
tell application appName
set mydoc to document docName
set wordcount to count of words of mydoc
log "wordcount = " & wordcount
return wordcount
end tell
end wordCount
However when I try the equivalent using the scripting bridge all my objects seem to have null contents. My code is as follows:
+ (NSUInteger) wordCountForApp: (SBApplication*) sbApp docNamed: (NSString*) docName
{
PagesApplication *pages = (PagesApplication*)sbApp;
PagesDocument *doc = [[pages documents] objectWithName:docName];
PagesText *text = [doc bodyText];
SBElementArray *words = [text words];
NSUInteger wc = [words count];
NSLog(#"Pages word count = %ul", (unsigned int) wc);
return wc; // wc comes back as zero always ... grrrr
}
I have verified that I am running this stuff on the main thread (and that equivalent code works against TextEdit). Any ideas as to what is going on/how to work around?
Thanks for having read this far....
That code works for me. The equivalent in F-Script:
> pages := SBApplication applicationWithBundleIdentifier: 'com.apple.iWork.Pages'
> (pages documents objectWithName: 'fun') bodyText words count
303
I'd suggest you step through it with a debugger and make sure that each object is what you're expecting, i.e. pages, [pages documents], etc.
If you're writing this code for external use, ideally you should not refer to documents by name; the user may have multiple documents with the same name open.
Another option is objc-appscript, which provides an neat ASTranslate utility that transforms AppleScript into Objective-C (or Ruby or Python for the other appscript bindings). For example, for the above, you'd have something like:
#import "PGGlue/PGGlue.h"
PGApplication *pages = [PGApplication applicationWithName: #"Pages"];
PGReference *ref = [[pages documents] byName: #"fun"];
PGCountCommand *cmd = [[ref count] each: [PGConstant word]];
id result = [cmd send];
So the problem was that I was asking for a document named "something.rtf" that I had just opened in Pages. But when Pages opens "something.rtf" it names it "something". And then when you ask for document named "something.rtf" it does not return nil because the document does not exist by that name. Instead, it returns a PagesDocument named "something.rtf" which has no valid contents: a NIL document. Which I guess I just was too stupid to recognize when I submitted to SO.
I have since checked other apps and this seems to be normal applescript behavior when you ask for a document by name (to get back a "valid object" containing a NIL document) oh well.
I am constructing a tuning fork app. The fork should allow up to 12 preset pitches.
Moreover, I wish to allow the user to choose a theme. Each theme will load a set of presets (not necessary to use all of them).
My configuration file would look something like this*:
theme: "A3"
comment: "An octave below concert pitch (ie A4 440Hz)"
presets: {
A3 220Hz=220.0
}
// http://en.wikipedia.org/wiki/Guitar_tuning
theme: "Guitar Standard Tuning"
comment:"EADGBE using 12-TET tuning"
presets: {
E2=82.41
A2=110.00
D3=146.83
G3=196.00
B3=246.94
E4=329.63
}
theme: "Bass Guitar Standard Tuning"
comment: "EADG using 12-TET tuning"
presets: {
E1=41.204
A2=55.000
D3=73.416
G3=97.999
}
...which need to be extracted into some structure like this:
#class Preset
{
NSString* label;
double freq;
}
#class Theme
{
NSString* label;
NSMutableArray* presets;
}
NSMutableArray* themes;
How do I write my file using JSON? ( I would like to create a minimum of typing on the part of the user -- how succinct can I get it? Could someone give me an example for the first theme? )
And how do I parse it into the structures using https://github.com/johnezang/JSONKit?
Here's a valid JSON example based on your thoughts:
[
{
"name": "Guitar Standard Tuning",
"comment": "EADGBE using 12-TET tuning",
"presets": {
"E2": "82.41",
"A2": "110.00",
"D3": "146.83",
"G3": "196.00",
"B3": "246.94",
"E4": "329.63"
}
},
{
"name": "Bass Guitar Standard Tuning",
"comment": "EADG using 12-TET tuning",
"presets": {
"E1": "41.204",
"A1": "55.000",
"D2": "73.416",
"G2": "97.999"
}
}
]
Read a file and parse using JSONKit:
NSData* jsonData = [NSData dataWithContentsOfFile: path];
JSONDecoder* decoder = [[JSONDecoder alloc]
initWithParseOptions:JKParseOptionNone];
NSArray* json = [decoder objectWithData:jsonData];
After that, you'll have to iterate over the json variable using a for loop.
Using the parser in your question and assuming you have Simeon's string in an NSString variable. Here's how to parse it:
#import "JSONKit.h"
id parsedJSON = [myJSONString objectFromJSONString];
That will give you a hierarchy of arrays and dictionaries that you can walk to get your Preset and Theme objects. In the above case, you would get an array with two dictionaries each with a name, comment and presets key. The first two will have NSString values and the third (presets) will have a dictionary as it's value with the note name as keys and the frequencies as values (as NSString objects).