iPhone CoreData join - sqlite

this is my core data model:
I'm trying to get all LanguageEntries from a database for a given category.categoryName and languageset.languageSetName e.g.
NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"LanguageEntry" inManagedObjectContext:del.managedObjectContext];
[fetchRequest setEntity:entity];
NSString* predicateString = [NSString stringWithFormat:#"Category.categoryName = %# AND LanguageSet.languageSetName = %#",
#"Food", #"English####Spanish"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:predicateString];
NSError *error = nil;
NSArray* objects = [del.managedObjectContext executeFetchRequest:fetchRequest error:&error];
This always returns 0 objects. If I set the predicate string to match on one relationship (e.g. Category.categoryName = Food or languageSet.languageSetName = English####Spanish) it will return data.
This is baffling, can anyone shed some light?
->Ken

Your can't think of Core Data as SQL. There is no such thing as a "join" in Core Data. In this case, your trying to find the intersection of two sets of objects. Close to a join logically but not in the implementation details. And the programming devil is always in the details.
Try using the logical equal "==" like so:
#"Category.categoryName == %# AND LanguageSet.languageSetName == %#"
I believe that will solve your problem.
The data model has a predicate editor hidden way in it. It can help you set up predicates even if you don't embed them in fetches in model itself. Just select an entity, in your case "LanguageEntity", then add a Fetch Request. The edit predicate will appear and you can use the dialog to create the predicate. It will display a textual version of the predicate that you can copy into your code.

The predicate properly wasn't created correctly, you must pass the parameters to predicateWithFormat. It should have been:
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"Category.categoryName = %# AND LanguageSet.languageSetName = %#",
#"Food",
#"English####Spanish"];
In case you were wondering what that does is it puts quotes around the string parameters automatically which are required when using a string in a predicate. When you created the query using NSString's format method that did not put the required quotes in.

Related

How to display date in RDLC in another language

I want to display date in RDLC(Report Definition Language Client-side) as १०/०७/२०१० instead 10/07/2010. How can i do this?
I believe it is not possible - at least not without effort on your side. Native digits are defined in .NET FW like:
var culture = new CultureInfo("km-KH");
for (var i = 0; i < culture.NumberFormat.NativeDigits.Length; i++) {
Console.Out.WriteLine(culture.NumberFormat.NativeDigits[i]);
}
BUT native digits formatting is not supported (yet).
Reference:
http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.digitsubstitution.aspx
The DigitSubstitution property is reserved for future use. Currently,
it is not used in either parsing or formatting operations for the
current NumberFormatInfo object.
You still can manage to do it on your own - i.e. add Report->Report properties->Code
Function Khmer(value)
value = Replace(value,"0","០")
value = Replace(value,"1","១")
value = Replace(value,"2","២")
value = Replace(value,"3","៣")
value = Replace(value,"4","៤")
value = Replace(value,"5","៥")
value = Replace(value,"6","៦")
value = Replace(value,"7","៧")
value = Replace(value,"8","៨")
value = Replace(value,"9","៩")
Khmer = value
End Function
Note - report code uses vb syntax (always) - dunno why.
And in your report add expression for the field you want to encode to Khmer native digits:
=Code.Khmer(Fields!DateCreated.Value)

stringByAddingPercentEscapesUsingEncoding adds unexpected characters?

I'm having a hard time getting my NSURL to work, when I create the final string before converting to URL it adds unwanted character to the end of the string, why is this happening and how can I fix it?
Here is my code:
NSString *remotepathstring = [[NSString alloc] init];
remotepathstring=newdata.remotepath;
NSLog(#"remotepathstring = %#",remotepathstring);
NSString *remotepathstringwithescapes = [remotepathstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"remotepathstring = %#",remotepathstringwithescapes);
remotepathURL =[NSURL URLWithString:remotepathstringwithescapes];
NSLog(#"RemotePathUrl=%#",remotepathURL);
Log outputs as follows:
"remotepathstring = http://nalahandthepinktiger.com/wp-content/uploads/nalah-sheet-5.pdf‎"
"remotepathstring = http://nalahandthepinktiger.com/wp-content/uploads/nalah-sheet-5.pdf%E2%80%8E"
"RemotePathUrl=http://nalahandthepinktiger.com/wp-content/uploads/nalah-sheet-5.pdf%E2%80%8E"
The sequence %E2%80%8E is a Unicode LEFT-TO-RIGHT MARK. This is present in your original remotepathstring, but invisible when printed out via NSLog.
The question becomes: how does newdata.remotepath get populated in the first place? Somewhere along the line it sounds like you need to perform some extra cleanup of input strings to strip out such a character.
Unrelated to the core question, it would seem you're a newcomer to Objective-C. This code is redundant and wasteful:
NSString *remotepathstring = [[NSString alloc] init];
remotepathstring=newdata.remotepath;
You create a string, only to immediately throw it away and replace it with another. If you're not using ARC, this has the additional problem of leaking! Instead do:
NSString *remotepathstring = newdata.remotepath;

Type Provider not seen by reflection

I'm trying to write my first type provider and am wondering if someone could point where I am going wrong.
I've used the freebase sample to work from. I've tried to sift thru the essential bits to get something very basic instantiated but obviously missed something or not got it quite right (perhaps in relation to the namespace). I'm simply trying to get this line working
type tp = MyFirstTypeProvider.DataProvider<username="username",password="password",product=prodId>
Intellisense is seeing the DataProvider, but I'm getting squiggly saying that a reference to the type can be found the type could not be found in the assembly.
namespace MyFirstProvider
type internal MyFirstRuntimeInfo(config: TypeProviderConfig) =
let runtimeAssembly = Assembly.LoadFrom(config.RuntimeAssembly)
member val DataContextType = runtimeAssembly.GetType("MyFirstProvider.Runtime.DataContext")
member this.RuntimeAssembly = runtimeAssembly
// This type defines the type provider. When compiled to a DLL, it can be added
// as a reference to an F# command-line compilation, script, or project.
[<TypeProvider>]
type public Types(config: TypeProviderConfig) as this =
inherit TypeProviderForNamespaces()
let bfRuntimeInfo = MyFirstRuntimeInfo(config)
let rootNamespace = "MyFirstProvider"
let defaultUsername = "xxxxxxxxxxx"
let defaultPassword = "yyyyyyyyyy"
let defaultProductId = -1
let defaultToken = "none"
let createDataContext = bfRuntimeInfo.DataContextType.GetMethod("_Create")
let createTypes(username, password, productId, rootTypeName) = let bf = new MyFirstProvider.Requests.Queries(defaultToken)
let schema = new MyFirstProvider.Schema.SchemaConnection(bf)
let rootType = ProvidedTypeDefinition(bfRuntimeInfo.RuntimeAssembly,rootNamespace,rootTypeName,baseType=Some typeof<obj>, HideObjectMethods=true)
let theServiceType = ProvidedTypeDefinition("Service",baseType=Some bfRuntimeInfo.DataContextType, HideObjectMethods=true)
let theServiceTypesClass = ProvidedTypeDefinition("ServiceTypes",baseType=Some typeof<obj>,HideObjectMethods=true)
theServiceTypesClass.AddMembers [ theServiceType ]
rootType.AddMembers [ theServiceTypesClass ]
rootType.AddMembersDelayed (fun () ->
[ yield ProvidedMethod ("GetDataContext", [], theServiceType, IsStaticMethod=true,
InvokeCode = (fun _args -> Expr.Call(createDataContext, [ Expr.Value defaultUsername; Expr.Value defaultPassword; Expr.Value defaultProductId ])))
])
rootType
let MyFirstType = createTypes(defaultUsername, defaultPassword, defaultProductId, "Data")
let paramMyFirstType = ProvidedTypeDefinition(bfRuntimeInfo.RuntimeAssembly, rootNamespace, "DataProvider", Some(typeof<obj>), HideObjectMethods = true)
let usernameParam = ProvidedStaticParameter("username", typeof<string>, defaultUsername)
let passwordParam = ProvidedStaticParameter("password", typeof<string>, defaultPassword)
let productIdParam = ProvidedStaticParameter("productId", typeof<int>, defaultProductId)
do paramMyFirstType.DefineStaticParameters([usernameParam;passwordParam;productIdParam], fun typeName providerArgs ->
let username = (providerArgs.[0] :?> string)
let password = (providerArgs.[1] :?> string)
let productId = (providerArgs.[2] :?> int)
createTypes(username, password, productId, typeName))
do
this.AddNamespace(rootNamespace, [MyFirstType ] )
this.AddNamespace(rootNamespace, [paramMyFirstType ] )
[<assembly:TypeProviderAssembly>]
do()
Many thx in advance.
When I try compiling your type provider and reference it in a script file, the reference #r "provider.dll" is underlined with a red squiggly that says:
The type provider 'MyFirstProvider.Types' reproted an error: The type provider constructor has thrown an exception: Object reference not set to an instance of an object.
You can debug such errors by starting a second instance of Visual Studio, and attaching the debugger to another instance (Debug -> Attach to Process) and opening the script file in the instance being debugged.
In the sample you posted here, the null reference exception occurs on this line:
let createDataContext = bfRuntimeInfo.DataContextType.GetMethod("_Create")
This is trying to access method that does not exist. I think the Freebase sample is relatively complicated starting point (here, it is using an object to represent the "data context" - you might want to follow that pattern, but I think it is easier to build it from scratch rather than adapting an existing code). I think a good starting point might be the Hello World type provider which is a lot simpler and just shows how to generate new types, properties and methods.
I would suggest, if you are looking for a simple example of type provider, to look at the File System type provider This is a good place to start as it has no state and no dependency management to take care of.
As to why this one has a dll it can not find, I think it is because this dll has to be seen from where your type provider's dll is. That is, for instance, in the same directory. (You can try to set "copy local" in the build process?)

Core Data, problems when saving or retrieving, don't know where it is

I'm quite new with Core Data, and I'm having an issue that I don't understand. I don't know what's going wrong.
I'm saving into my Persistent Store, 7 objects of an entity "Weight" that is read from a JSON file with this code:
for (NSDictionary *values in aWeightValues)
{
weightValues = [NSEntityDescription insertNewObjectForEntityForName:#"Weight"
inManagedObjectContext:moc];
[weightValues setValue:[typeWeight objectForKey:#"unit"] forKey:#"unit"];
[weightValues setValue:[values objectForKey:#"timestamp"] forKey:#"date"];
[weightValues setValue:[values objectForKey:#"value"] forKey:#"amount"];
if (![moc save:&error])
{
NSLog(#"Problem saving: %#", [error localizedDescription]);
}
}
The for loop makes 7 loops, that means it's being saved correctly (speaking about the number of objects).
But then, when I try to retrieve data from the Persistent Store in this way:
-(NSMutableArray *) extractWeightEntities
{
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
NSError *error;
NSManagedObjectContext *moc = [appDelegate managedObjectContext];
NSEntityDescription *entityWeight = [NSEntityDescription entityForName:#"Weight" inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc]init]autorelease];
[request setEntity:entityWeight];
entityWeight = nil;
fetchResult = [[moc executeFetchRequest:request error:&error]mutableCopy];
return (fetchResult);
}
and try to show one attribute of each object retrieved, I get 1044 rows in my TableView!! when I should have just 7.
What am I doing wrong? Is the problem when I'm saving, or when I'm retrieving?
I hope you can help to solve this issue. Many thanks in advance!!
You don't need to call save on each iteration of the loop, this is very inefficient. Save afterwards.
Put a breakpoint on you loop and ensure it is only going over it 7 times.
Is the data continuously accumulating? Are you deleting the app each time? If you keep running the code - it will keep adding objects to your datastore unless you check if they exist in the datastore before inserting them.

NSLog NSRange problem

I have a NSSting resultcontent that contains html data which is dynamic and length of html data is always different according to user input.
I could insert my html data in SQLite3 by replacing " from NSString. Now the problem is that SQlite3 doesn't have any inbuilt function to find the position of a particular substring. In SQL you can use CHARINDEX or Patindex for this purpose.
Now I am trying to find the position of this substring "sphinx". I tried NSrange, substringWithRange etc. but I am not getting the exact start and end positions of this substring. How do you show NSRange in console by using NSLog. Here is my code
//find substring "sphinx"
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"sphinx"
options:NSRegularExpressionCaseInsensitive
error:&error];
//Get total length of resultcontent (NSString which contains whole html code)
NSInteger lengthTotal=[resultContent length];
NSLog(#"lengthTotal is %i", lengthTotal);
// Get NSRange
NSRange rangeOfSubstring = [regex rangeOfFirstMatchInString:resultContent
options:0
range:NSMakeRange(0, lengthTotal)];
NSString *substringData = [resultContent substringWithRange:rangeOfSubstring];
if (!NSEqualRanges(rangeOfSubstring, NSMakeRange(NSNotFound, 0)))
{
NSString *substringData = [resultContent substringWithRange:rangeOfSubstring];
NSLog(#"substringData is %#", substringData);
[b] // so far it works fine and shows substringData ="sphinx" in Console
//But folowing line doesn't show start and end position of substringData "sphinx"
NSLog([#"range of substring is =%#",[resultContent substringWithRange:rangeOfSubstring] ];[/b]
}
How do I find the exact position of a substring from NSString? I also tried %S in NSLog but no results.
I also have the same NSString resultcontent Data in SQLite table (text datatype). How do you find index of a character or position of a substring in Sqlite without Charindex and patindex function. As html code is dynamic and length varies according to the user input so I need to know the index or position of substring after each user input.

Resources