Using Kii Query Result - ios

I am running a Kii Query that returns the expected number of results. However the results array contains object formatted as follow
"<KiiObject: 0x130471ae0>"
this is the output from
NSLog(#"%#",results);
I am confident that the Query is working correctly as i can add and remove objects from the bucket and the number of results in the array changes according, i just don't know how to take the results and get the corresponding object.
I have gone over everything in the Kii Doc's
link to Kii Docs
The result is to short to be the object id(uuid string) and i can't find any other reference in the docs that makes sense.

You can refer to bellow snippet
NSError *error = nil;
// Build "all" query
KiiQuery *allQuery = [KiiQuery queryWithClause:nil];
// Create an array to store all the results in
NSMutableArray *allResults = [NSMutableArray array];
// Create a placeholder for any paginated queries
KiiQuery *nextQuery;
// Get an array of KiiObjects by querying the bucket
NSArray *results = [bucket executeQuerySynchronous:allQuery
withError:&error
andNext:&nextQuery];
if (error != nil) {
// Error handling
return;
}
//obtain single KiiObject
KiiObject* firstObject = allResults.firstObject; // now you should get all the object properties
NSLog(#"MaxScore : %#",[firstObject getObjectForKey:#"maxScore"]); //i.e to get "maxScore" value
Below is the links for querying KiiObjects.
http://docs.kii.com/en/guides/ios/managing-data/object-storages/querying/

Related

Core Data, Get Sum Of Certain Boolean Value Attribute

I'm logging a Core Data attribute "passed" (Boolean value)
for (Circuit *object in self.distributionBoard.circuits) {
NSLog(#"Core Data Value = %d", object.passed);
}
This logs fine. What's the most efficient way to count the number of times the saved boolean value == 1?
Using NSFetchReques or NSExpression did not yield the desired result so far. Looked here: Core Data sum of all instances attribute and similar, with the usual searches
Since your property is a boolean, you can make it a lot simpler than the methods described in that answer. Use a predicate to match the value of passed and then get the count of the result instead of the fetched objects. Something like:
NSFetchRequest<Event *> *fetchRequest = MyEntity.fetchRequest;
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"passed = true"];
NSError *error = nil;
NSUInteger count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];
Then count has the number of instances where passed is true.

How can I implement my logic properly to populate my UITableView

Sorry guys, this problem I am running into is pretty trivial. I just can't wrap my head around it so hope someone can help me. Your help is really appreciated. I am getting JSON data through NSURLConnectDelegate with a web API. I get something like this back:
(
{
id = 340
name = Vicent },
{
id = 339
name = Johny },
{
id = 338
name = Eric }
)
and I save it in a NSMutableArray as a global variable. Now, I have a NSSet of "ids". For example:
{
340, 339
}
In the numberOfRowsInSection, I return the set's count. I am trying to load only the ids in the NSSet from the array with the data saved from the webAPI, so I do something like this in cellForRowIndexPath:
for (NSNumber *num in [set allObjects]) {
NSString *newString = [[savedArray objectAtIndex:indexPath.row]
NSString *new = [num stringValue];
if ([new isEqual:newString]) {
}}
How can I just populate the ids I want?
The JSON makes it look like you have an array of dictionaries, which is a reasonable data structure to use as the data source for a table view.
It sounds like you're trying to filter your array to only include the items that are in your set. Is that right?
If so, you could write code that would create a new array containing the subset of your array elements who's ID is also in your set. There are at least a half-dozen ways to do that. One fairly simple approach would be to use the NSArray method indexesOfObjectsPassingTest. You'd pass that method a block of code that would check each array element to see if it's id object was in your set.
That would give you an NSIndexSet with the indexes of the items in your array who's ID are in your set. Then you could use the NSArray method objectsAtIndexes to get an array of only the objects that are also in the set. Something like this (Assuming that your array of dictionaries is called savedArray and your set is called allObjects:
//get the indexes of items in the array savedArray who's id appears in the set allObjects
NSIndexSet *indexes = [savedArray indexesOfObjectsPassingTest:
^(NSDictionary *obj,
NSUInteger idx,
BOOL *stop)
{
return [allObjects member: obj[#"id"]] != nil;
}
];
//Now build an (immutable) array of just the objects who's ID are in the set
NSArray *subArray = [savedArray objectsAtIndexes: indexes];
The array subArray created above is immutable. If you need a mutable array you would need to make a mutable copy, which is a one-line change.
Disclaimer: I still struggle a little with block syntax, so the above might not be exactly correct, but it gives you the general idea.

Parse bool from JSON

I am trying to parse the multiple bool values. In below code JSONObject is the NSMutableArray.ii is the indexpath. But with the below am getting only one value. This is first time to me handling bool values from json, help me to fetch the bool values inside the answer list array.
BOOL options= [[[jsonObject objectAtIndex:ii] objectForKey:#"Is_Correct"]boolValue] ;
NSLog(#"correct answer %d",options);
NSDictionary* outerArrayElement = jsonObject[1];
NSArray* amswersList = outerArrayElement["AnswersList"];
NSDictionary* innerArrayElement = answersList[0];
NSNumber* is_correctNum = innerArrayElement["Is_Correct"];
BOOL is_correct = [is_correctNum].boolValue;
But one should iterate over the arrays, and also check for nil results in some cases, especially when retrieving the outer array element.
And for testing insert NSLog statements after each step.

How to check if NSDictionay key has a value efficiently when creating XML

I am creating some XML in objective C, I know how to do it however there is the possibility that there could be 800+ values I might be putting into XML, which I am getting from a NSArray of NSDictionaries.
So I was wondering if there is an efficient way of checking for nill or null in a keyvalue that's of type NSString.
Currently this is what my code looks like:
NSMutableArray *xmlItems = [coreDataController readInstallForXML:selectedInstallID];
for (int i = 0; i < [xmlItems count]; i++) {
NSDictionary *currentXMLItem = [xmlItems objectAtIndex:i];
[xmlWriter writeStartElement:#"Items"];
[xmlWriter writeAttribute:#"insID" value:[currentXMLItem valueForKey:#"insID"]];
// there are about another 20 attributes I have to add here.
}
// then write end elemtent etc.
In the code above I have no added any checking but I was hoping someone might have something better for me than adding a bunch of if statements for each attribute.
You can use [NSDictionary allKeysForObject:] to get all keys for the 'nil' values, so you have a list of keys to ignore.
Generating 800 items is not necessarily 'much' or 'slow'. You don't want to do that on the main thread anyway, so just make sure you perform it as a background operation.
use the allKeys method on the NSDictionary to return an NSArray of keys; then iterate through that array and for each key retrieve the value from the dictionary and use one if statement to check the string before writing out the xml element

Programmatically update duplicate values in coredata?

I am new in Core Data. I want to update duplicate values. For example my table looks like this
id | Name
============
1 | Joseph
2 | Fernandez
3 | Joseph
4 | James
Say that I want to update Joseph corresponding to id 1 and 4 to "myName". When I tried to update this it only updates the 4th row. I can't find any way to do this in any of the documentation. Can anyone suggest me a solution?
One more question, how can I print all name values?
you will have to read over the documentation to know how to update record
http://www.appcoda.com/core-data-tutorial-update-delete/
James,
I'll try to reply to both your questions with sample code.
To update specific objects you need to se up a new NSFetchRequest with a predicate, grab the objects (of type NSManagedObject), update the values you are interested in and save the context.
So, for example:
NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"YourEntityName"];
// set the predicate (it's equal to set a WHERE SQL clause) filtering on the name for example
// use camel case notation if possible, so instead of Name use name (for this you have to changes your model, if you don't want to do it use Name)
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"name == %#", #"Joseph"]];
NSError* error = nil;
NSArray* results = [context executeFetchRequest:fetchRequest error:&error];
// do some error checking here...
for (NSManagedObject resultItem in results) {
// use KVC (for example) to access your object properties
[resultItem setValue:#"myName" forKey:#"name"];
}
// save your context here
// if you don't save, changes are not stored
To print you need to se up a new NSFetchRequest, grab the objects (of type NSManagedObject) and use NSLog.
So for example:
NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"YourEntityName"];
NSError* error = nil;
NSArray* results = [context executeFetchRequest:fetchRequest error:&error];
// do some error checking here...
for (NSManagedObject resultItem in results) {
NSLog(#"%#", [resultItem valueForKey:#"name"]);
}
P.S. The code I provided is quite simple and the predicate I used to specific values check against the name. Since this could be error prone, I would modify the model and using a sort of guid for each objects you need to use (I don't know if id is for that but I would change its name to another one, for example userId). Once done you can check against it.
Hope that helps.
It's as simple as retrieving the NSManagedObject and changing the Name property. You can retrieve the NSManagedObject with a fetch request. Once you changed the property and you want to keep it changed even when you close the application you'll have to do a save on the managedObjectContext.
You'll have to read over the documentation to get up to speed on core data:
http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/CoreData/Articles/cdBasics.html#//apple_ref/doc/uid/TP40001650-TP1
Edit: just NSLog whatever you want to know, for example log you fetch request results.

Resources