I tried to add object to my mutable array using TFHlle parse html in this code but it return null for object in my array, but in the for loop, I log the result of '[element objectForKey:#"title"]' and it returns result I want.
How I can add the result of element [objectForKey:#"title"] to my array?
TFHpple *htmlParseResult = [TFHpple hppleWithHTMLData:self.responseData];
NSString *coursesXpathQueryString = #"//h2[#class='main']/a";
NSArray *coursesNodes = [htmlParseResult searchWithXPathQuery:coursesXpathQueryString];
NSMutableArray *fitCourse = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in coursesNodes) {
[fitCourse addObject:[element objectForKey:#"title"]];
}
I think
NSArray *coursesNodes = [htmlParseResult searchWithXPathQuery:coursesXpathQueryString];
should be change to:
NSArray *coursesNodes = [NSArray arrayWithArray:[htmlParseResult searchWithXPathQuery:coursesXpathQueryString]];
I am not sure this works but you can try.
Related
I need to use some core data managed objects in an NSOperation. The problem is that core data is not thread safe and apparently the object can't be loaded from the new thread. Does anybody know a good tutorial for this? I need the object read only... so the thread will not modify them in any way. Some other, unrelated entities may be added on the main thread while these objects are used in the background, but the background entities don't need to be modified at all..
Hmm seemed I fixed the background running issue, but now the problem is nothing is returned to the delegate... Why? In the thred if I nslog the results are all shown but that call to the delegate never happens
This is the code:
-(void)evaluateFormula:(Formula *)frm runNo:(NSUInteger)runCount{
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue setMaxConcurrentOperationCount:2];
NSManagedObjectID *formulaId = frm.objectID;
for (int i = 0; i < runCount; i++) {
NSInvocationOperation * op = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(runFormula:) object:formulaId];
[queue addOperation:op];
}
}
-(void)runFormula:(NSManagedObjectID *)fId {
NSManagedObjectContext *thredContext =[[NSManagedObjectContext alloc] init];
NSPersistentStoreCoordinator *coord = (NSPersistentStoreCoordinator *)[(PSAppDelegate *)[[UIApplication sharedApplication] delegate] persistentStoreCoordinator];
[thredContext setPersistentStoreCoordinator:coord];
Formula *f = (Formula *)[thredContext objectWithID:fId];
NSDictionary *vars = [self evaluateVariables:[f.hasVariables allObjects]];
NSMutableString *formula = [NSMutableString stringWithString:f.formula];
for (NSString *var in [vars allKeys]) {
NSNumber *value =[vars objectForKey:var];
[formula replaceOccurrencesOfString:var withString:[value stringValue] options:NSCaseInsensitiveSearch range:NSMakeRange(0, [formula length])];
}
//parse formula
NSNumber *result = [formula numberByEvaluatingString];
// NSLog(#" formula %# result : %d",formula,[result intValue]);
//aggregate results
[self performSelectorOnMainThread:#selector(aggregate:) withObject:result waitUntilDone:YES]; // the delegate doesn't get called ...
}
-(void)aggregate:(NSNumber *)res {
[self.delegate didReceiveResult:res];
}
I need to check if a string in my array is empty using the NSComparisonPredicate. The predicate that is being executed is: string MATCHES[c] ""
But nothing shows up in the results, it does not list my empty strings.
Is my predicate wrong or there is just another way of dealing with empty strings with NSPredicate?
I'm not sure why you're using NSComparisonPredicate ,I've never used that one, so I'm not familiar with it. Have you tried predicateWithFormat?
NSPredicate *pred = [NSPredicate predicateWithFormat:#"self.length == 0"];
It's not clear how you want to use the predicate, but this should work if you're using it to filter an array.
If you want to know the indexes of strings in your array that are empty, then you could use indexesOfObjectsPassingTest: like so:
NSIndexSet *indxs = [array indexesOfObjectsPassingTest:^BOOL(NSString *aString, NSUInteger idx, BOOL *stop) {
return aString.length == 0;
}];
NSLog(#"%#",indxs);
As rdelmar mentions above, for such a task you should just check the length of the string by string.length==0
You can filter your array using blocks. I would recommend that approach against using NSPredicate. Here is some sample code:
//creating array
NSArray *myArray = [NSArray arrayWithObjects:#"a", #"b", #"", #"c", nil];
//filtering
NSIndexSet *iset = [myArray indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
NSString *str = obj;
return !str.length;
}
];
//creating my result array with empty strings
NSArray *emptyStrings = [myArray objectsAtIndexes:iset];
//logging all strings
for (NSString *str in myArray) {
NSLog(#"string: %#", str);
}
//logging empty strings
for (NSString *str in emptyStrings) {
NSLog(#"empty string: %#", str);
}
EDIT:
If you really need to use NSComparisonPredicate, here it is:
NSExpression *left = [NSExpression expressionForKeyPath:#"length"];
NSExpression *right = [NSExpression expressionForConstantValue:[NSNumber numberWithInt:0]];
NSComparisonPredicateModifier modifier = NSDirectPredicateModifier;
NSPredicateOperatorType operator = NSEqualToPredicateOperatorType;
NSPredicate *predicate = [NSComparisonPredicate predicateWithLeftExpression:left rightExpression:right modifier:modifier type:operator options:0];
NSArray *filtered = [myArray filteredArrayUsingPredicate:predicate];
I would like to know if it's possible to init a subclass of NSManagedObject ?
I have a class "Actualite" which is a subclass of NSManagedObject and when I want to initialize this class, I get this error :
"CoreData: error: Failed to call designated initializer on NSManagedObject class Actualite", and the app crashes after this message "-[Actualite setTitre:]: unrecognized selector sent to instance 0x8433be0"
Here is my code :
-(void) recupererActualites {
listeNouvellesActualites = [[NSMutableArray alloc] init];
// Convert the supplied URL string into a usable URL object
NSURL *url = [NSURL URLWithString:FACE06_RSS];
// Create a new rssParser object based on the TouchXML "CXMLDocument" class, this is the
// object that actually grabs and processes the RSS data
CXMLDocument *rssParser = [[CXMLDocument alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding options:0 error:nil];
// Create a new Array object to be used with the looping of the results from the rssParser
NSArray *resultNodes = NULL;
// Set the resultNodes Array to contain an object for every instance of an node in our RSS feed
resultNodes = [rssParser nodesForXPath:#"//item" error:nil];
NSMutableArray* tmp = [[NSMutableArray alloc] init];
for (CXMLElement* resultElement in resultNodes) {
// Create a temporary MutableDictionary to store the items fields in, which will eventually end up in blogEntries
NSMutableDictionary *blogItem = [[NSMutableDictionary alloc] init];
NSMutableArray* categories = [[NSMutableArray alloc] init];
// Create a counter variable as type "int"
int counter;
// Loop through the children of the current node
for(counter = 0; counter < [resultElement childCount]; counter++) {
// Add each field to the blogItem Dictionary with the node name as key and node value as the value
if([[[resultElement childAtIndex:counter] name] isEqual:#"category"])
[categories addObject:[[resultElement childAtIndex:counter] stringValue]];
else {
if ([[resultElement childAtIndex:counter] stringValue] != nil)
[blogItem setObject:[[resultElement childAtIndex:counter] stringValue] forKey:[[resultElement childAtIndex:counter] name]];
else
[blogItem setObject:#"" forKey:[[resultElement childAtIndex:counter] name]];
}
}
Actualite* actu = [[Actualite alloc] init];
[blogItem setObject:categories forKey:#"categories"];
[actu initWithDictionnary:blogItem];
[tmp addObject:actu];
//[actu release];
[categories release];
[blogItem release];
}
listeNouvellesActualites = tmp;
[rssParser release];
resultNodes = nil;
// Stockage des actualités en local
[self stockerActualites];
}
And the initWithDictionary method set all the attributes of the Actualite class.
I also tried
Actualite* actu = [[Actualite alloc] initWithEntity:[NSEntityDescription entityForName:#"Actualite" inManagedObjectContext:managedObjectContext] insertIntoManagedObjectContext:managedObjectContext];
and
Actualite* actu = (Actualite*)[NSEntityDescription entityForName:#"Actualite" inManagedObjectContext:managedObjectContext];
instead of
Actualite* actu = [[Actualite alloc] init];
The errors disappear but the app stops at this point. I don't know what can I do...
Is someone already had this problem ?
Thanks a lot !
The idea is that you ask for a new object to be created inside a context and then you use it:
Actualite* actu = [NSEntityDescription insertNewObjectForEntityForName:#"Actualite" inManagedObjectContext:managedObjectContext];
I have been trying to add an object as an NSMutableDictionary to my array, which I am accessing from another view, and It doesn't seem to work. I want to be able to store the data in a plist which I access from a NSDictionary.
-(void)saveAlarm:(id)sender {
// Adding object for alarm to AlarmViewController
alarmArrayCopy = alarmViewController.alarmsTime;
NSMutableDictionary *newAlarm = [[NSMutableDictionary alloc] init];
[newAlarm setValue:labelTextField.text forKey:LABEL_KEY];
[newAlarm setValue:alarmPicker.date forKey:TIME_KEY];
[alarmArrayCopy addObject:(newAlarm)];
// Dismissing and tiding up.
[self.navigationController dismissModalViewControllerAnimated:YES];
[newAlarm release];
}
UPDATE: How do I add an NSDictionary to my plist database (my db is an array)?
Here is some new code, I updated the NSMutableDictionary to NSDictionary because in my plist you can only have normal dictionaries not a mutable one. But now it crashed and gives me a Thread 1:Program received signal: "SIGABRT".
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"data.plist"];
// Adding object for alarm to AlarmViewController
NSDictionary *newAlarm = [[NSDictionary alloc] init];
[newAlarm setValue:labelTextField.text forKey:LABEL_KEY];
[newAlarm setValue:[NSString stringWithFormat:#"%#", alarmPicker.date] forKey:TIME_KEY];
[newAlarm writeToFile:finalPath atomically:NO];
or
-(IBAction)saveAlarm:(id)sender {
// Adding object for alarm to AlarmViewController
NSString *time = [NSString stringWithFormat:#"%#", alarmPicker.date];
NSString *label = [NSString stringWithFormat:#"%#",labelTextField.text];
NSDictionary *newAlarm = [[NSDictionary alloc] initWithObjectsAndKeys:label, LABEL_KEY,time, TIME_KEY, nil];
self.alarmArrayCopy = alarmViewController.alarmsTime;
[alarmArrayCopy addObject:(newAlarm)];
// Dismissing and tiding up.
[newAlarm release];
[self.navigationController dismissModalViewControllerAnimated:YES];
}
First, you should use setObject:forKey: method for adding objects to NSMutableDictionary. Second, you should use initWithObjectsAndKeys: method if you are using NSDictionary.
The setValue:forKey is a method of the Key Value Coding protocol. That was described at here “
Where's the difference between setObject:forKey: and setValue:forKey: in NSMutableDictionary?
”
So, you should do that,
NSDictionary *newAlarm = [[NSDictionary alloc] initWithObjectsAndKeys:
labelTextField.text, LABEL_KEY,
alarmPicker.date, TIME_KEY, nil];
[newAlarm setValue:alarmPicker.date forKey:TIME_KEY];
I am not quite sure, but I guess your error is because you can't send an instance of NSDate object to setValue:forKey method. You may use either setObject:forKey or change NSDate to NSString by [NSString stringWithFormat:"%#", alarmPicker.date].
Hope that helps.
I know I shouldn't look at Core Data as something relational. But with a SQL query it is easiest to explain what I'm trying to do.
What I'd like to do is get the max value from a property constrained to the children of an entity. In SQL something like: select max(valueY) from graphdata where parentID = 10
I'm doing something akin to the above SQL query successfully excluding the where (NSPredicate) part.
I added the NSPredicate to my code thinking it would exclude the graphdata objects not within the KPI I'm looking at. Well, guess not, it's not what I'm seeing, it seems to do nothing at all really.
The Core Data Model consistst of multiple KPI objects, each containing an Array of GraphData objects. Every GraphData object contains a valueX and a valueY property.
I want the max valueY for the graphdata of a specified KPI object.
Here's my code, it's based on one of Apple's core data snippets:
NSManagedObjectContext *context = ...
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:GRAPH_DATA_ENTITY_NAME inManagedObjectContext:context];
[request setEntity:entity];
// Specify that the request should return dictionaries.
[request setResultType:NSDictionaryResultType];
// Create an expression for the key path.
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:#"ValueY"];
//MY WHERE KIND OF CLAUSE/PREDICATE WHICH ISN'T WORKING?
NSPredicate *predicate =
[NSPredicate predicateWithFormat:#"kpiForGraphData == %#", self.kpi];
[request setPredicate:predicate];
// Create an expression to represent the function you want to apply
NSExpression *expression = [NSExpression expressionForFunction:#"max:"
arguments:[NSArray arrayWithObject:keyPathExpression]];
// Create an expression description using the minExpression and returning a date.
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
// The name is the key that will be used in the dictionary for the return value.
[expressionDescription setName:#"maxValueY"];
[expressionDescription setExpression:expression];
[expressionDescription setExpressionResultType:NSDecimalAttributeType]; // For example, NSDateAttributeType
// Set the request's properties to fetch just the property represented by the expressions.
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
// Execute the fetch.
NSError *error;
id requestedValue = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
// Handle the error.
}
else {
if ([objects count] > 0) {
requestedValue = [[objects objectAtIndex:0] valueForKey:#"maxValueY"];
}
}
[expressionDescription release];
[request release];
return [requestedValue doubleValue];
So far I've been trying to help myself by reading docs, searching through Google and stackoverflow. Everything I seem to find either selects entities (NSPredicates) or selects values using a function. Never have I seen an example or an explanation doing what I'd like to do. I like Core Data, but right now SQL seems way more straightforward to me.