Skip to content

Instantly share code, notes, and snippets.

@alanthonyc
Created December 5, 2011 19:02
Show Gist options
  • Save alanthonyc/1434791 to your computer and use it in GitHub Desktop.
Save alanthonyc/1434791 to your computer and use it in GitHub Desktop.
Objective-C Scratchpad - a bunch of random stuff
// read plist
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSString *plistPath;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
plistPath = [rootPath stringByAppendingPathComponent:@"Pexplorer.plist"];
NSString *originalPlistPath;
originalPlistPath = plistPath;
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
plistPath = [[NSBundle mainBundle] pathForResource:@"Pexplorer" ofType:@"plist"];
}
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSMutableDictionary *temp = (NSMutableDictionary *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&errorDesc];
if (!temp) {
NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
}
NSDate *lastRefreshDate = [[NSDate alloc] init];
NSMutableDictionary *plistDict = [NSDictionary dictionaryWithDictionary:[temp objectForKey:@"Root"]];
lastRefreshDate = [plistDict objectForKey:@"LastRefreshDate"];
hasChanged = [lastUpdateDate compare:lastRefreshDate];
if (hasChanged == NSOrderedAscending) {
[[self navigationItem] setTitle:@"Pins Changed"];
} else {
[[self navigationItem] setTitle:@"No Changes"];
}
///////////////////
NSMutableDictionary *newPlistDict = [NSMutableDictionary dictionaryWithDictionary:plistDict];
[newPlistDict setValue:dateNow forKey:@"LastRefreshDate"];
[temp setValue:plistDict forKey:@"Root"];
NSData *plistUpdate = [NSPropertyListSerialization dataFromPropertyList:temp
format:NSPropertyListXMLFormat_v1_0
errorDescription:&errorDesc];
if (plistUpdate) {
if (![plistUpdate writeToFile:originalPlistPath atomically:YES]) {
NSLog(@"write error");
}
} else {
NSLog(@"plist serialization error...");
}
//////////
- (void)loadPinsEvent:(id)sender
{
[[self navigationItem] setTitle:@"Title Reset"];
// Initialize table view if empty.
if ([pinList count] == 0) {
[self loadPins];
[[self tableView] reloadData];
} else { // otherwise, add more entries to end of list
// create a request for entries earlier than earliest pin displayed
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSDate *earliestPinDate = [[pinList objectAtIndex:[pinList count]-1] pinDate];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Pin"
inManagedObjectContext:moc];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
initWithKey:@"pinDate" ascending:NO];
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"(pinDate < %@)", earliestPinDate];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[request setEntity:entity];
[request setPredicate:predicate];
[request setFetchLimit:20];
// execute fetch
NSError *error = nil;
NSMutableArray *newPinList = [[moc executeFetchRequest:request error:&error] mutableCopy];
if (newPinList == nil) {
// error ...
}
// insert new pins into pinlist
NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithObjects: nil];
NSInteger newRowIndex = [pinList count];
NSInteger newPinCount = [newPinList count];
for (NSInteger pinCount = 0; pinCount < newPinCount; pinCount++) {
[pinList insertObject:[newPinList objectAtIndex:pinCount] atIndex:newRowIndex];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:newRowIndex inSection:0];
[insertIndexPaths addObject:indexPath];
newRowIndex += 1;
}
// animate cell insertions
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView endUpdates];
}
}
// If active text field is hidden by keyboard, scroll it so it's visible
// Your application might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, passwordTextField.frame.origin) ) {
}
CGPoint scrollPoint = CGPointMake(0.0, passwordTextField.frame.origin.y+kbSize.height-80);
[tempScrollView setContentOffset:scrollPoint animated:YES];
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
UIScrollView *tempScrollView=(UIScrollView *)self.view;
tempScrollView.contentInset = contentInsets;
tempScrollView.scrollIndicatorInsets = contentInsets;
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
UIScrollView *tempScrollView=(UIScrollView *)self.view;
tempScrollView.contentInset = contentInsets;
tempScrollView.scrollIndicatorInsets = contentInsets;
}
UIScrollView *tempScrollView=(UIScrollView *)self.view;
tempScrollView.contentSize=CGSizeMake(320,460);
/*
==========
Old parser
==========
*/
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
if ([elementName isEqual:@"post"]) {
NSLog(@".");
if (titleString && pinUrl) {
NSDictionary *pinDict = [[NSDictionary alloc] initWithObjectsAndKeys:titleString, @"title", pinUrl, @"pinUrl", pinDate, @"datetime", nil];
[pinList addObject:pinDict];
// Check to see if url is already in database.
BOOL pinUrlFound;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Pin"
inManagedObjectContext:moc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"(url == %@)", pinUrl];
[request setEntity:entity];
[request setPredicate:predicate];
// execute fetch
NSError *fetchError = nil;
NSArray *recordsForPinUrl = [moc executeFetchRequest:request error:&fetchError];
pinUrlFound = NO;
if (recordsForPinUrl == nil) {
// error ...
} else {
NSInteger pinCount = [recordsForPinUrl count];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *date = [dateFormatter dateFromString:[pinDict objectForKey:@"datetime"]];
if (pinCount > 0) {
// Update pin in moc with new info.
for (NSInteger currentPin = 0; currentPin < pinCount; currentPin++) {
Pin *pin = [recordsForPinUrl objectAtIndex:currentPin];
[pin setPinDate:date];
[pin setTitle:[pinDict objectForKey:@"title"]];
}
} else {
// Add new pin to moc.
Pin *pin = (Pin *)[NSEntityDescription insertNewObjectForEntityForName:@"Pin"
inManagedObjectContext:moc];
[pin setPinDate:date];
[pin setTitle:[pinDict objectForKey:@"title"]];
[pin setUrl:[pinDict objectForKey:@"pinUrl"]];
}
}
titleString = nil;
pinUrl = nil;
pinDate = nil;
}
postFound = NO;
}
}
////// Refresh Protocol declaration and implementation
// protocol declaration in class using protocol
@protocol FullRefreshDelegate <NSObject>
- (void)startFullRefresh;
- (void)endFullRefresh;
- (void)updateFullRefreshProgress;
@end
@interface FullRefreshViewController : UIViewController
{
id <FullRefreshDelegate> delegate;
IBOutlet UIProgressView *refreshProgress;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
refreshProgress = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
}
return self;
}
// protocol implementation in calling class
#pragma Full Refresh Protocol Methods
- (void)startFullRefresh
{
[pinRequest requestAllPins];
progress = 0.0;
}
- (void)endFullRefresh
{
progress = 1.0f;
[self.refreshConfirmVC.refreshProgress setProgress:progress animated:YES];
/* for (progress = 0.0; progress <= 4.0; progress += 0.0001) {
[self.refreshConfirmVC.refreshProgress setProgress:progress animated:YES];
NSLog(@"Refreshing %f.", progress);
}*/
[self.refreshConfirmVC dismissModalViewControllerAnimated:YES];
}
- (void)updateFullRefreshProgress
{
if (progress >= 1.0) {
[self endFullRefresh];
} else {
progress += 0.1;
[self.refreshConfirmVC.refreshProgress setProgress:progress animated:YES];
}
}
/////// From Stackoverflow, predicates for group-by
// start by retrieving day, weekday, month and year components for today
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todayComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:[NSDate date]];
NSInteger theDay = [todayComponents day];
NSInteger theMonth = [todayComponents month];
NSInteger theYear = [todayComponents year];
// now build a NSDate object for the input date using these components
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:theDay];
[components setMonth:theMonth];
[components setYear:theYear];
NSDate *thisDate = [gregorian dateFromComponents:components];
[components release];
// now build a NSDate object for tomorrow
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate:thisDate options:0];
[offsetComponents release];
NSDateComponents *tomorrowComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:nextDate];
NSInteger tomorrowDay = [tomorrowComponents day];
NSInteger tomorrowMonth = [tomorrowComponents month];
NSInteger tomorrowYear = [tomorrowComponents year];
[gregorian release];
// now build the predicate needed to fetch the information
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"DateAttribute < %@ && DateAttribute > %@", nextDate, thisDate];
//////////
- (void)calculateLocalPinCountsByDate
{
moc = [[NSManagedObjectContext alloc] init];
[self.moc setPersistentStoreCoordinator:self.psc];
// clear all objects
NSFetchRequest *dateCounts = [[NSFetchRequest alloc] init];
[dateCounts setEntity:[NSEntityDescription entityForName:@"Pin" inManagedObjectContext:moc]];
NSExpression *ex = [NSExpression expressionForFunction:@"count:" arguments:[NSArray arrayWithObject:[NSExpression expressionForKeyPath:@"pinDate"]]];
NSExpressionDescription *countED = [[NSExpressionDescription alloc] init];
[countED setExpression:ex];
[countED setExpressionResultType:NSInteger16AttributeType];
[countED setName:@"dateCount"];
// [dateCounts setResultType:NSCountResultType];
// [dateCounts setPropertiesToFetch:[NSArray arrayWithObjects:@"pinDate", @"count", nil]];
[dateCounts setPropertiesToFetch:[NSArray arrayWithObjects:countED, @"pinDate", nil]];
[dateCounts setPropertiesToGroupBy:[NSArray arrayWithObject:@"pinDate"]];
[dateCounts setResultType:NSDictionaryResultType];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"pinDate" ascending:NO];
[dateCounts setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSDateFormatter *pinDateFormatter = [[NSDateFormatter alloc] init];
[pinDateFormatter setDateStyle:NSDateFormatterLongStyle];
NSError *fetchError = nil;
NSArray *pinsByDate = [moc executeFetchRequest:dateCounts error:&fetchError];
if (pinsByDate) {
for (NSDictionary *d in pinsByDate) {
NSNumber *temp = [d objectForKey:@"dateCount"];
NSLog(@"Date: %@", [pinDateFormatter stringFromDate:[d objectForKey:@"pinDate"]]);
NSLog(@"Count: %d", [temp intValue]);
}
} else {
NSLog(@"Fetch failed.");
}
}
// Reload full table.
- (void)AllPinsFromDateReceived:(NSNotification *)notification
{
// get the pinrequest object
PinRequest *recentPinsList = [notification object];
NSData *tempData = [recentPinsList xmlData];
// create parser object
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:tempData];
dispatch_async(parseQueue,
^{
moc = [[NSManagedObjectContext alloc] init];
[self.moc setPersistentStoreCoordinator:self.psc];
// New parsing code
PinParser *pinParser = [[PinParser alloc] init];
[parser setDelegate:pinParser];
[parser parse];
for (NSDictionary *pinDict in [pinParser pinList]) {
NSDate *datetime = [datetimeFormatter dateFromString:[pinDict objectForKey:@"datetime"]];
NSDate *pinDate = [dateFormatter dateFromString:[pinDict objectForKey:@"date"]];
// Add new pin to moc.
Pin *pin = (Pin *)[NSEntityDescription insertNewObjectForEntityForName:@"Pin"
inManagedObjectContext:moc];
[pin setPinDate:pinDate];
[pin setPinDatetime:datetime];
[pin setTitle:[pinDict objectForKey:@"title"]];
[pin setUrl:[pinDict objectForKey:@"pinUrl"]];
NSString *domainName = [pinDict objectForKey:@"domain"];
NSFetchRequest *pinDomain = [[NSFetchRequest alloc] init];
[pinDomain setEntity:[NSEntityDescription entityForName:@"Domain"inManagedObjectContext:moc]];
[pinDomain setIncludesPropertyValues:NO];
NSPredicate *domainNamePredicate = [NSPredicate predicateWithFormat:@"(name == %@)", domainName];
[pinDomain setPredicate:domainNamePredicate];
NSError *pinDomainFindError = nil;
NSArray *pinDomainFind = [moc executeFetchRequest:pinDomain error:&pinDomainFindError];
if ([pinDomainFind count] == 0) {
Domain *domain = (Domain *)[NSEntityDescription insertNewObjectForEntityForName:@"Domain" inManagedObjectContext:moc];
[domain setName:domainName];
NSMutableSet *domainPins = [domain mutableSetValueForKey:@"pins"];
[domainPins addObject:pin];
} else {
Domain *domain = [pinDomainFind objectAtIndex:0];
NSMutableSet *domainPins = [domain mutableSetValueForKey:@"pins"];
[domainPins addObject:pin];
}
}
Log *logEntry = (Log *)[NSEntityDescription insertNewObjectForEntityForName:@"Log" inManagedObjectContext:moc];
[logEntry setType:@"Refresh"];
[logEntry setDate:[NSDate date]];
// Save moc
NSError *error;
if (![moc save:&error]) {
NSLog(@"Error saving moc 'Request From Date'.");
// error handling...
}
NSLog(@"Parsing complete.");
// notify!
[[NSNotificationCenter defaultCenter] postNotificationName:@"PinListParseDidComplete" object:self];
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment