2016-10-24 3 views
0

3000 일 연속으로 데이터 배열을 만들려고하지만이 코드는 하나의 단일 날짜에서 3000 번만 데이터를 추출합니다. 계속 증가하는 날짜 (theincreasingnumberofdays)를 인쇄 할 때마다 루프가 반복 될 때마다 날짜가 하루 더 늘어나는 것을 볼 수 있습니다. 그러나 루프 이후에 배열을 읽을 때 모든 데이터는 동일한 3000 번입니다.여러 연속 날짜에서 데이터를 가져 오려고 시도합니다.

class day 
{ 
var week: Int? 
var date: Int? 
var month: Int? 
var year: Int? 
var weekday: Int? 
} 


@IBAction func pressbuttontodefinearray(sender: AnyObject) { 
    print("button has been pressed") 

    if (theArrayContainingAllTheUserData.count > 1) { 
     print("array contains something allready and we don't do anything") 
     return 
    } 

    print("array is empty and we're filling it right now") 
    var ScoopDay = day() 

    var numberofloops = 0 

    while theArrayContainingAllTheUserData.count < 3000 
    { 
     var theincreasingnumberofdays: NSDate { 
      return NSCalendar.current.date(byAdding: .day, value: numberofloops, to: NSDate() as Date)! as NSDate 
     } 

     print(theincreasingnumberofdays) 

     let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! 

     // var thenextdate = calendar.date(byAdding: .day, value: numberofloops, to: date as Date) 
     numberofloops=numberofloops+1 
     ScoopDay.week=Int(myCalendar.component(.weekday, from: theincreasingnumberofdays as Date!)) 
     ScoopDay.date=Int(myCalendar.component(.day, from: theincreasingnumberofdays as Date!)) 
     ScoopDay.month=Int(myCalendar.component(.month, from: theincreasingnumberofdays as Date!)) 
     ScoopDay.year=Int(myCalendar.component(.year, from: theincreasingnumberofdays as Date!)) 
     ScoopDay.weekday=Int(myCalendar.component(.weekday, from: theincreasingnumberofdays as Date!)) 

     theArrayContainingAllTheUserData.append(ScoopDay) 
    } 

    print("we're done with this looping business. Let's print it") 
    var placeinarray = 0 
    while placeinarray < 2998 
    { 
     print("Here is", placeinarray, theArrayContainingAllTheUserData[placeinarray].date, theArrayContainingAllTheUserData[placeinarray].month) 
     placeinarray=placeinarray+1 
    } 

    return 
} 
+0

사이드 참고 : 귀하의 루프는 매우이다 비싼. 예를 들어 같은 유형의 3000 개의 캘린더 인스턴스를 생성하고 있으며 모든 수신 된 구성 요소는 어쨌든 'Int'입니다. – vadian

답변

2

문제는 ScoopDay라는 이름의 한 day 객체 있다는 것입니다, 당신은 그 배열에 하나의 객체 3000 번 추가됩니다. 그래서 배열은 하나의 단일 객체에 대한 3000 개의 참조로 끝납니다. 마지막으로 할당 한 값이 들어 있습니다.

당신은 루프 내부의 라인

var ScoopDay = day() 

를 이동하여이 문제를 해결할 수 있습니다. 그렇게하면 3000 개의 서로 다른 내용을 가진 day 개체를 만들 수 있습니다.

의 발 빠른 스타일 팁 : 클래스 이름의 첫 글자를 대문자로, 그래서, 변수 이름의 첫 글자를 소문자 :

class Day 

var scoopDay = Day() 
+0

당신은 선생님입니다! 고맙습니다! –

+0

여러분을 환영합니다! 귀하의 질문에 대한 답변을 얻은 경우 질문에 답변으로 표시하십시오. - 감사합니다! –