Esempio n. 1
0
		void AddDataPointsForChart (DateTime XValue, Double YValue)
		{
			NSCalendar cal 			= new NSCalendar (NSCalendarType.Gregorian);
			NSDateComponents comp 	= new NSDateComponents ();
			comp.Day 				= XValue.Day;
			comp.Month 				= XValue.Month;
			comp.Year 				= XValue.Year;
			comp.Hour 				= XValue.Hour;
			comp.Minute 			= XValue.Minute;
			comp.Second 			= XValue.Second;
			DataPoints.Add (new SFChartDataPoint ( cal.DateFromComponents(comp), NSObject.FromObject(YValue)));
		}
		private void AddEarthquakesToList (List<Earthquake> earthquakes)
		{
			var entity = NSEntityDescription.EntityForName ("Earthquake", managedObjectContext);
			var fetchRequest = new NSFetchRequest ();
			fetchRequest.Entity = entity;

			var date = (NSPropertyDescription)entity.PropertiesByName.ValueForKey (new NSString ("date"));
			var location = (NSPropertyDescription)entity.PropertiesByName.ValueForKey (new NSString ("location"));

			fetchRequest.PropertiesToFetch = new NSPropertyDescription[] { date, location }; 
			fetchRequest.ResultType = NSFetchRequestResultType.DictionaryResultType;

			NSError error;

			foreach (var earthquake in earthquakes) {
				var arguments = new NSObject[] { earthquake.Location, earthquake.Date };
				fetchRequest.Predicate = NSPredicate.FromFormat (@"location = %@ AND date = %@", arguments);
				var fetchedItems = NSArray.FromNSObjects (managedObjectContext.ExecuteFetchRequest (fetchRequest, out error));

				if (fetchedItems.Count == 0) {

					if (string.IsNullOrEmpty (entity.Description))
						continue;

					var managedEarthquake = new ManagedEarthquake (entity, managedObjectContext) {
						Magnitude = earthquake.Magnitude,
						Location = earthquake.Location,
						Date = earthquake.Date,
						USGSWebLink = earthquake.USGSWebLink,
						Latitude = earthquake.Latitude,
						Longitude = earthquake.Longitude
					};

					managedObjectContext.InsertObject (managedEarthquake);
				}

				var gregorian = new NSCalendar (NSCalendarType.Gregorian);
				var offsetComponents = new NSDateComponents ();
				offsetComponents.Day = -14;// 14 days back from today
				NSDate twoWeeksAgo = gregorian.DateByAddingComponents (offsetComponents, NSDate.Now, NSCalendarOptions.None);

				// use the same fetchrequest instance but switch back to NSManagedObjectResultType
				fetchRequest.ResultType = NSFetchRequestResultType.ManagedObject;
				fetchRequest.Predicate = NSPredicate.FromFormat (@"date < %@", new NSObject[] { twoWeeksAgo });

				var olderEarthquakes = NSArray.FromObjects (managedObjectContext.ExecuteFetchRequest (fetchRequest, out error));
				
				for (int i = 0; i < olderEarthquakes.Count; i++) {
					managedObjectContext.DeleteObject (olderEarthquakes.GetItem<ManagedEarthquake> (i));
				}

				if (managedObjectContext.HasChanges) {
					if (!managedObjectContext.Save (out error))
						Console.WriteLine (string.Format ("Unresolved error {0}", error.LocalizedDescription));
				}
			}
		}