使用 (NSDate Predicate) 过滤 NSArray,直到整个数组被过滤
filter NSArray using (NSDate Predicate) until the whole Array is filtered
我很难在标题中定义我的问题所以如果我的标题不合适那么请纠正我好吧所以我有一个
NSArray
named results
从 CoreData
中获取,在这个数组中,项目有 date
键,它是 NSDate 类型。我想根据 Date
键上的月份来断言 NSArray
,并且我能够手动完成这就是我这样做的方式:
let predicated = NSPredicate(format: "date >= %@ AND date <= %@", start, End)
var filtered = results.filteredArrayUsingPredicate(predicated)
这里 start
和 end
是 NSdate
,它们是给定月份的第一个和最后一个日期,假设我预测类似 "give me the results which are between 1 jan to 31 jan" 的东西并且它工作正常
但我想以某种方式断言我的整个 result
数组,这样我就不必提供日期范围,就像一个函数,它将采用 NSArray
并给我输出带有月份变量的
func filterResultArray(NSArray) -> name of months with results {
// here predicate the whole array and add them to the founded months variable
}
print( "\(filterResultArray(resultsArray) )") // should print :
jan = 5 , feb = 18 , march = 5 , may = 87
请告诉我我尝试使用这种方法做什么是可能的还是不可能的,如果是的话请给我一些提示或指导,告诉我我将如何做这对我很有帮助
为了更好地理解请看例子:
example - myArray = [ "1,01,2016", "4,01,2016" ,"28,01,2016", "6,02,2016" "25,02,2016", "29,02,2016" "4,03,2016", "4,04,2016" "10,04,2016", "24,04,2016" "9,05,2016", "29,05,2016" "17,05,2016", "24,05,2016" "12,06,2016", "13,06,2016" ]
现在我该如何过滤这个数组,这样我才能得到类似于这样的结果:
January = 3
feb = 3
march = 1
april = 3
may = 4
june = 2
@Joshua 向您展示的解决方案看起来非常优雅 - 假设您只对月份感兴趣 - 这意味着 2016 年 3 月与 2015 年 3 月一样 - 然后当您将数据解析为 myArray
,只需创建一个 myMonths
数组并去掉中间的数据元素即可得到月份。
它看起来像这样 -
let dateComponents = resultDate.componentsSeparatedByString(",")
myMonths.append(dateComponents[1])
如果您 需要在计数中包含年份,则只需附加字符串即可得到 "201603"
或 "032016"
我很难在标题中定义我的问题所以如果我的标题不合适那么请纠正我好吧所以我有一个
NSArray
named results
从 CoreData
中获取,在这个数组中,项目有 date
键,它是 NSDate 类型。我想根据 Date
键上的月份来断言 NSArray
,并且我能够手动完成这就是我这样做的方式:
let predicated = NSPredicate(format: "date >= %@ AND date <= %@", start, End)
var filtered = results.filteredArrayUsingPredicate(predicated)
这里 start
和 end
是 NSdate
,它们是给定月份的第一个和最后一个日期,假设我预测类似 "give me the results which are between 1 jan to 31 jan" 的东西并且它工作正常
但我想以某种方式断言我的整个 result
数组,这样我就不必提供日期范围,就像一个函数,它将采用 NSArray
并给我输出带有月份变量的
func filterResultArray(NSArray) -> name of months with results {
// here predicate the whole array and add them to the founded months variable
}
print( "\(filterResultArray(resultsArray) )") // should print :
jan = 5 , feb = 18 , march = 5 , may = 87
请告诉我我尝试使用这种方法做什么是可能的还是不可能的,如果是的话请给我一些提示或指导,告诉我我将如何做这对我很有帮助
为了更好地理解请看例子:
example - myArray = [ "1,01,2016", "4,01,2016" ,"28,01,2016", "6,02,2016" "25,02,2016", "29,02,2016" "4,03,2016", "4,04,2016" "10,04,2016", "24,04,2016" "9,05,2016", "29,05,2016" "17,05,2016", "24,05,2016" "12,06,2016", "13,06,2016" ]
现在我该如何过滤这个数组,这样我才能得到类似于这样的结果:
January = 3
feb = 3
march = 1
april = 3
may = 4
june = 2
@Joshua 向您展示的解决方案看起来非常优雅 - 假设您只对月份感兴趣 - 这意味着 2016 年 3 月与 2015 年 3 月一样 - 然后当您将数据解析为 myArray
,只需创建一个 myMonths
数组并去掉中间的数据元素即可得到月份。
它看起来像这样 -
let dateComponents = resultDate.componentsSeparatedByString(",")
myMonths.append(dateComponents[1])
如果您 需要在计数中包含年份,则只需附加字符串即可得到 "201603"
或 "032016"