2017-03-14 4 views
1

칼로리, 지방, 탄수화물 및 단백질을 보유하는 사용자 지정 Struct 클래스가 있습니다.STRUCT Array to UserDefaults

사용자 변수

var theArray : NSMutableArray = [] 

struct CFCPstruct { 
    let calories : Int! 
    let fats : Int! 
    let carbs : Int! 
    let protein: Int! 
    init(Calories: Int, Fats: Int, Carbs: Int, Protein: Int) { 
     self.calories = Calories 
     self.fats = Fats 
     self.carbs = Carbs 
     self.protein = Protein 
    } 
} 

let addLog = [CFCPstruct(Calories: totalCalories, Fats: totalFats, Carbs: totalCarbs, Protein: totalProtein)] 

에 I가 넣어 데이터를 입력 할 때마다 이제도 모두 저장 배열을 만들었다. 그런 다음 모든 값을 배열에 저장 한 다음이를 UserDefaults에 저장해야합니다.

그럼 내가 전화 후 [0]라고 할 수있는 사용자 기본 설정 전화 배열을 호출하고 각 칼로리, 탄수화물이 필요합니다 ... 뭔가를 thelog.calories // theology.carbs 등

답변

2

가 할 수있는 NSCoding을 사용하십시오. 오브젝트는 클래스 여야합니다. 그러나 모든 값이 속성 목록을 준수하므로 변수 dictionaryRepresentation과 해당 이니셜 라이저를 추가 할 수 있습니다. 모든 스위프트의 결코 사용 NSMutableArray

첫째는 비 선택적 초기화 초기화됩니다 암시 풀어 옵션 등의 변수를 선언하지.

var theArray = [CFCPstruct]() 

struct CFCPstruct { 
    let calories : Int 
    let fats : Int 
    let carbs : Int 
    let protein: Int 

    init(calories: Int, fats: Int, carbs: Int, protein: Int) { 
     self.calories = calories 
     self.fats = fats 
     self.carbs = carbs 
     self.protein = protein 
    } 

    init(dictionary : [String:Int]) { 
     self.calories = dictionary["calories"]! 
     self.fats = dictionary["fats"]! 
     self.carbs = dictionary["carbs"]! 
     self.protein = dictionary["protein"]! 
    } 

    var dictionaryRepresentation : [String:Int] { 
     return ["calories" : calories, "fats" : fats, "carbs" : carbs, "protein" : protein] 
    } 
} 

이제 사용자 기본값에서 배열을 읽고 쓸 수 있습니다. 당신은 당신의 데이터 배열을 만든 경우

func saveDefaults() 
{ 
    let cfcpArray = theArray.map{ $0.dictionaryRepresentation } 
    UserDefaults.standard.set(cfcpArray, forKey: "cfcpArray") 
} 

func loadDefaults() 
{ 
    theArray = (UserDefaults.standard.object(forKey: "cfcpArray") as! [[String:Int]]).map{ CFCPstruct(dictionary:$0) } 
} 
-1

이제, 당신은 다음과 같이 저장할 수 있습니다 : -

할 yourArrayOfDict = [[ "A": "스미스", "B" "UK"], [ "A": "폴", "B" "UAE"]

스위프트 3

let defaults = UserDefaults.standard 
defaults.set(yourArrayOfDict, forKey: "customKey_SavedArray") 
당신이 print(s) 배열이 저장됩니다 보장 할 수 있도록,의에 가치를 얻을 것이다

let s = defaults.value(forKey: "customKey_SavedArray") 
print(s) 

: 이제

, 당신은에 의해 그들에게에 액세스 .

스위프트 2 :

let defaults = NSUserDefaults.standardUserDefaults() 
defaults.setValue(yourArrayOfDict, forKey: "customKey_SavedArray") 

액세스 그들에게는 :

let s = defaults.objectForKey("customKey_SavedArray") as? [[String:AnyObject]] 

자, 여기들 그래서 당신이 사용하여 액세스 할 수 없습니다, 데이터의 배열로서 가치를 보유하고 당신이 말한대로 let first_item = s[0], 또는 for in을 사용하여 배열의 항목을 반복 할 수 있습니다. 루프.