본문 바로가기

IOS

Property List(.plist) 2

이전 글에서는 property list에 root의 type을 Dictionary로 설정하고, 그 Dictionary 안에 key, value로 값을 설정한 뒤, 코드로 Bundle.main을 이용해서 property list안의 Dictionary의 값을 가져와보는 코드를 작성했습니다.

 

이번에는 다른 타입(Array)로 설정하고 그 값을 가져와서 label의 text로 설정해주는 코드를 작성해보겠습니다.

 

1. 

먼저 이전 글에서 생성했던 Property list 파일로 이동해서 Root의 Type을 Array로 변경합니다.

 

해당 파일을 수정 후 Open As > Source code로 열어보면 XML에 <dictionary></dictionary>였던 부분이 <array></array>로 바뀌고 설정한 값과 타입이 들어가 있는 것을 확인할 수 있습니다.

 

2.

이전 글에서 Root의 Type이 Dictionary일 때 다음과 같은 형태로 Bundle.main에서 생성했던 Property list의 파일명과 확장자로 url을 얻어온 후 해당 url을 파라미터로 하는 관련 타입(NSDictionary)의 생성자(init(contentOf:error:))를 통해 dictionary에 접근할 수 있었습니다.

 guard let url = Bundle.main.url(forResource: "Data", withExtension: "plist") else { return }
 
if let dictionary = try? NSDictionary(contentsOf: url, error: ()) {
	//TODO: - access dictionary
}

 

이를 응용하면 다음과 같이 작성해볼 수 있습니다.

if let array = try? NSArray(contentsOf: url, error: ()) {
    //index + down casting
    if let item = array[0] as? String {
        print(item)
    }

    //down casting
    if let firstItem = array.firstObject as? String {
        print("firstObject", firstItem)
    }

    //casting
    let itemList = array as Array

    //index + down casting
    if let item = itemList[0] as? String {
        print("itemList index",item)
    }
    
    //access array element + down casting
    if let firstObject = itemList.first as? String {
        print("item List First", firstObject)
    }

    textLabel.text = someValue
}

Root의 Type이 Array일 땐 NSArray생성자로 값에 접근할 수 있고, 위의 코드와 같이 다양한 방식으로 접근해봤을 때 접근 가능함을 확인했고 마지막에 label의 text로 set해주면 다음과 같이 Property list에 설정한 값으로 textLabel의 text가 변경됨을 확인할 수 있습니다.

 

위의 코드 주석에도 작성했지만 접근 가능한 방식은 여러 가지였지만 접근했을 때 값이 Any 또는 AnyObject타입이여서 down casting이 반드시 필요했습니다. 값의 사용 시 이 점을 주의해서 사용해야겠습니다.🙂

 

참고:

Property list 공식문서

https://swieeft.github.io/2021/09/07/PropertyListRead.html

Kxcoding

'IOS' 카테고리의 다른 글

DispatchworkItem  (0) 2023.08.17
Property List(.plist) 1  (0) 2023.08.09