Docs Menu
Docs Home
/ /
데이터 유형

딕셔너리 (Dictionaries) - React Native SDK

버전 realm@10.5.0의 새로운 기능

Realm.Dictionary 데이터 유형 사용하여 값과 쌍을 이루는 고유한 문자열 키 컬렉션 관리 할 수 있습니다. dictionary 데이터는 Javascript 객체 유형에 매핑됩니다.

예를 들어, home 속성이 dictionary 타입으로 정의된 HomeOwner Realm 객체를 생성하는 방법은 다음과 같습니다.

realm.create('HomeOwner', {
name: 'Anna Smith',
home: {address: '2 jefferson lane', yearRenovated: 1994, color: 'blue'},
});

Realm 객체 모델에 대한 혼합 값 딕셔너리는 다음 세 가지 방법으로 정의할 수 있습니다.

  • 필드의 데이터 타입을 빈 객체 "{}"로 설정합니다.

  • 특정 타입의 값이 있는 딕셔너리를 생성하려면 괄호 앞에 데이터 타입을 추가하세요. 예를 들어, 딕셔너리 값이 정수여야 하면 "int{}"를 사용하고 딕셔너리 값이 문자열이어야 하면 "string{}"을 사용합니다.

  • 객체 유형을 명시적으로 정의합니다. 이는 Realm의 객체 유형을 사전 값으로 사용하는 데 필요합니다.

class HomeOwner extends Realm.Object {
static schema = {
name: 'HomeOwner',
properties: {
name: 'string',
home: '{}',
pets: {
type: 'dictionary',
objectType: 'Pet',
optional: true,
},
},
};
}

Realm.Dictionary 유형을 확장하는 인터페이스 를 사용하여 사전 객체의 구문을 정의합니다. 이 클래스의 모든 Realm 객체는 인터페이스에 지정된 구문을 따라야 합니다.

interface Home extends Realm.Dictionary {
address?: string;
color?: string;
price?: number;
yearRenovated?: number;
}
class HomeOwner extends Realm.Object<HomeOwner> {
name!: string;
home!: Home;
pets?: Pet[];
static schema: ObjectSchema = {
name: 'HomeOwner',
properties: {
name: 'string',
home: 'mixed{}',
pets: {
type: 'dictionary',
objectType: 'Pet',
optional: true,
},
},
};
}

Realm에서는 지도 키에 . 또는 $ 문자를 사용할 수 없습니다. 백분율 인코딩 및 디코딩을 사용하여 허용되지 않는 문자 중 하나가 포함된 지도 키를 저장할 수 있습니다.

// Percent encode . or $ characters to use them in map keys
const mapKey = "kitchen.windows";
const encodedMapKey = mapKey.replace(".", "%2E");

다음 CreateHomeOwner 예시에서는 딕셔너리 속성을 사용하여 새 객체를 생성합니다.

CreateHomeOwner 컴포넌트는 다음을 수행합니다.

  • 주택 소유자의 이름과 주소 나타내는 React 상태 각각 생성합니다.

  • 컴포넌트 내에서 useRealm() 훅을 호출하여 열린 realm 인스턴스에 대한 액세스 권한을 얻습니다.

  • 쓰기 트랜잭션(write transaction)을 수행하고 각각 주택 소유자 이름과 주소의 TextInput 값을 기반으로 새 HomeOwner 객체를 생성하는 컴포넌트 메서드 SubmitHomeOwner() 을(를) 생성하세요.

  • 제출 버튼에 SubmitHomeOwner()를 호출하는 onPress 이벤트 추가합니다.

1const CreateHomeOwner = () => {
2 const [homeOwnerName, setHomeOwnerName] = useState('John Smith');
3 const [address, setAddress] = useState('1 Home Street');
4 const realm = useRealm();
5
6 const submitHomeOwner = () => {
7 // Create a HomeOwner realm object within a Write Transaction
8 realm.write(() => {
9 realm.create('HomeOwner', {
10 name: homeOwnerName,
11 // For the dictionary field, 'home', set the value
12 // to a regular JavaScript object
13 home: {
14 address,
15 },
16 });
17 });
18 };
19 return (
20 <View>
21 <TextInput
22 value={homeOwnerName}
23 onChangeText={text => setHomeOwnerName(text)}
24 />
25 <TextInput value={address} onChangeText={text => setAddress(text)} />
26 <Button
27 title='Submit Home Owner'
28 onPress={submitHomeOwner}
29 />
30 </View>
31 );
32};

쿼리 필터하다 하려면 컬렉션 .filtered() 를 실행 하나 이상의 객체 속성 값을 기반으로 결과의 하위 집합을 지정합니다. 괄호 표기법을 사용하여 딕셔너리의 속성 값에 따라 결과를 지정할 수 있습니다.

<dictionary>.@keys 또는 <dictionary>.@values을 사용하여 결과 컬렉션에 특정 키나 값이 있는지 확인할 수도 있습니다. 예를 들어 중첩된 home 사전이 있는 HomeOwner 컬렉션이 있는 경우 home.@keys = "price" 쿼리를 실행하여 "price" 속성이 있는 home이 있는 모든 HomeOwner 객체를 반환할 수 있습니다.

다음 HomeList 예시에서는 딕셔너리 속성이 있는 객체를 쿼리합니다.

HomeList 컴포넌트는 다음을 수행합니다.

  • HomeOwner 클래스를 useQuery 훅에 전달하여 모든 주택 소유자에 대한 쿼리를 실행합니다.

  • collection.filtered()에 쿼리 home.@keys = "price"를 전달하여 등록된 가격이 있는 주택 소유자에 대한 쿼리를 수행합니다.

  • 대괄호 표기법을 사용해 collection.filtered()를 실행하여 주소가 "Summerhill St."로 설정된 첫 번째 주택 소유자를 찾고, 점 표기법을 사용하여 해당 집을 가져오는 방식으로 서머 힐 주택에 대한 쿼리를 수행합니다.

  • collection.filtered()에 쿼리 'home.@values = "red"'를 전달하여 값이 빨간색인 필드가 있는 모든 주택 소유자에 대한 쿼리를 수행합니다. 그러면 첫 번째 주택 소유주의 집이 표시됩니다.

  • 주택 정보를 렌더링하여 UI에 쿼리 결과를 표시합니다.

1const HomeList = () => {
2 // query for all HomeOwner objects
3 const homeOwners = useQuery(HomeOwner);
4
5 // run the `.filtered()` method on all the returned homeOwners to
6 // find all homeOwners that have a house with a listed price
7 const listedPriceHomes = useQuer(HomeOwner, homeOwners => {
8 return homeOwners.filtered('home.@keys = "price"');
9 });
10
11 // run the `.filtered()` method on all the returned homeOwners to
12 // find the house with the address "Summerhill St."
13 const summerHillHouse = useQuery(HomeOwner, homeOwners => {
14 return homeOwners.filtered('home["address"] = "Summerhill St."');
15 })[0].home;
16
17 // run the `.filtered()` method on all the returned homeOwners to
18 // find the first house that has any field with a value of 'red'
19 const redHouse = useQuery(HomeOwner, homeOwners => {
20 return homeOwners.filtered('home.@values = "red"');
21 })[0].home;
22
23 return (
24 <View>
25 <Text>All homes:</Text>
26 {homeOwners.map(homeOwner => (
27 <View>
28 <Text>{homeOwner.home.address}</Text>
29 </View>
30 ))}
31
32 <Text>All homes with a price:</Text>
33 {listedPriceHomes.map(homeOwner => (
34 <View>
35 <Text>{homeOwner.home.address}</Text>
36 <Text>{homeOwner.home.price}</Text>
37 </View>
38 ))}
39
40 <Text>Summer Hill House:</Text>
41 <Text>{summerHillHouse.address}</Text>
42 <Text>{summerHillHouse.color}</Text>
43
44 <Text>Red House:</Text>
45 <Text>{redHouse.address}</Text>
46 </View>
47 );
48};
1const HomeList = () => {
2 // query for all HomeOwner objects
3 const homeOwners = useQuery(HomeOwner);
4
5 // run the `.filtered()` method on all the returned homeOwners to
6 // find all homeOwners that have a house with a listed price
7 const listedPriceHomes = useQuery(HomeOwner, homeOwners => {
8 return homeOwners.filtered('home.@keys = "price"');
9 });
10
11 // run the `.filtered()` method on all the returned homeOwners to
12 // find the house with the address "Summerhill St."
13 const summerHillHouse = useQuery(HomeOwner, homeOwners => {
14 return homeOwners.filtered('home["address"] = "Summerhill St."');
15 })[0].home;
16
17 // run the `.filtered()` method on all the returned homeOwners to
18 // find the first house that has any field with a value of 'red'
19 const redHouse = useQuery(HomeOwner, homeOwners => {
20 return homeOwners.filtered('home.@values = "red"');
21 })[0].home;
22
23 return (
24 <View>
25 <Text>All homes:</Text>
26 {homeOwners.map(homeOwner => (
27 <View>
28 <Text>{homeOwner.home.address}</Text>
29 </View>
30 ))}
31
32 <Text>All homes with a price:</Text>
33 {listedPriceHomes.map(homeOwner => (
34 <View>
35 <Text>{homeOwner.home.address}</Text>
36 <Text>{homeOwner.home.price}</Text>
37 </View>
38 ))}
39
40 <Text>Summer Hill House:</Text>
41 <Text>{summerHillHouse.address}</Text>
42 <Text>{summerHillHouse.color}</Text>
43
44 <Text>Red House:</Text>
45 <Text>{redHouse.address}</Text>
46 </View>
47 );
48};

dictionary.set() 메서드 를 사용하여 딕셔너리의 속성을 업데이트합니다. 메서드 또는 점 표기법을 사용하여 해당 속성을 새 값으로 설정합니다.

다음 UpdateHome 예시에서는 딕셔너리의 속성을 업데이트합니다.

UpdateHome 컴포넌트는 다음을 수행합니다.

  • React 상태만들기
    .
  • 컴포넌트 내에서 useRealm() 훅을 호출하여 열려 있는 realm 인스턴스에 접근합니다.
    .
  • 쓰기 트랜잭션(write transaction)을 수행하는 구성 요소 메서드 updateAddress()를 생성합니다.
    dictionary.set()를 사용하여 집의 주소를 address 상태 변수의 값으로 설정합니다. 또한 점 표기법을 사용하여 yearRenovated2004로 설정합니다.
  • address 상태 변수를 표시하고 변경하는 TextInput을 렌더링합니다.

  • 다음에 onPress 이벤트 추가합니다.
    "주소 업데이트" 버튼을 클릭하여 다음을 호출합니다. updateAddress()
1const UpdateHome = ({homeOwnerName}) => {
2 const [address, setAddress] = useState('');
3 const realm = useRealm();
4 const homeOwner = useQuery(
5 HomeOwner,
6 homeOwners => {
7 return homeOwners.filtered(`name == '${homeOwnerName}'`);
8 },
9 [homeOwnerName],
10 )[0];
11
12 const updateAddress = () => {
13 // Update the home object with the new address
14 realm.write(() => {
15 // use the `set()` method to update a field of a dictionary
16 homeOwner.home.set({address});
17 // alternatively, update a field of a dictionary through dot notation
18 homeOwner.home.yearRenovated = 2004;
19 });
20 };
21
22 return (
23 <View>
24 <Text>{homeOwner.name}</Text>
25 <TextInput
26 value={address}
27 onChangeText={setAddress}
28 placeholder='Enter new address'
29 />
30 <Button
31 onPress={updateAddress}
32 title='Update Address'
33
34 />
35 </View>
36 );
37};
1const UpdateHome = ({homeOwnerName}: {homeOwnerName: string}) => {
2 const [address, setAddress] = useState('');
3 const realm = useRealm();
4 const homeOwner = useQuery(
5 HomeOwner,
6 homeOwners => {
7 return homeOwners.filtered(`name == '${homeOwnerName}'`);
8 },
9 [homeOwnerName],
10 )[0];
11
12 const updateAddress = () => {
13 // Update the home object with the new address
14 realm.write(() => {
15 // use the `set()` method to update a field of a dictionary
16 homeOwner.home.set({address});
17 // alternatively, update a field of a dictionary through dot notation
18 homeOwner.home.yearRenovated = 2004;
19 });
20 };
21
22 return (
23 <View>
24 <Text>{homeOwner.name}</Text>
25 <TextInput
26 value={address}
27 onChangeText={setAddress}
28 placeholder='Enter new address'
29 />
30 <Button
31 onPress={updateAddress}
32 title='Update Address'
33 />
34 </View>
35 );
36};

딕셔너리의 멤버를 삭제하려면 딕셔너리에서 제거할 속성의 배열과 함께 dictionary.remove() 메서드를 사용합니다.

다음 HomeInfo 예시에서는 딕셔너리의 멤버를 삭제합니다.

HomeInfo 컴포넌트는 다음을 수행합니다.

  • 컴포넌트 내에서 useRealm() 훅을 호출하여 열린 realm 인스턴스에 대한 액세스 권한을 얻습니다.

  • 컴포넌트에 prop으로 전달된 이름과 일치하는 첫 번째 주택 소유자를 조회합니다. useQuery(HomeOwner).filtered(`name == '${homeOwnerName}'`) 쿼리에서 반환된 첫 번째 값을 가져옴으로써 수행할 수 있습니다.

  • 쓰기 트랜잭션(write transaction)을 수행하는 컴포넌트 메서드 deleteExtraHomeInfo()를 생성하고 dictionary.remove()를 호출하여 yearRenovatedcolor 속성을 제거합니다.

  • UI에 집주인의 이름과 집 주소를 렌더링합니다.

  • deleteExtraHomeInfo()를 호출하는 ' 예비 집 정보 삭제' 버튼에 onPress 이벤트 추가합니다.

1const HomeInfo = ({homeOwnerName}) => {
2 const realm = useRealm();
3 const homeOwner = useQuery(
4 HomeOwner,
5 homeOwners => {
6 return homeOwners.filtered(`name == '${homeOwnerName}'`);
7 },
8 [homeOwnerName],
9 )[0];
10
11 const deleteExtraHomeInfo = () => {
12 realm.write(() => {
13 // remove the 'yearRenovated' and 'color' field of the house
14 homeOwner.home.remove(['yearRenovated', 'color']);
15 });
16 };
17
18 return (
19 <View>
20 <Text>{homeOwner.name}</Text>
21 <Text>{homeOwner.home.address}</Text>
22 <Button
23 onPress={deleteExtraHomeInfo}
24 title='Delete extra home info'
25
26 />
27 </View>
28 );
29};
1const HomeInfo = ({homeOwnerName}: {homeOwnerName: string}) => {
2 const realm = useRealm();
3 const homeOwner = useQuery(
4 HomeOwner,
5 homeOwners => {
6 return homeOwners.filtered(`name == '${homeOwnerName}'`);
7 },
8 [homeOwnerName],
9 )[0];
10
11 const deleteExtraHomeInfo = () => {
12 realm.write(() => {
13 // remove the 'yearRenovated' and 'color' field of the house
14 homeOwner.home.remove(['yearRenovated', 'color']);
15 });
16 };
17
18 return (
19 <View>
20 <Text>{homeOwner.name}</Text>
21 <Text>{homeOwner.home.address}</Text>
22 <Button
23 onPress={deleteExtraHomeInfo}
24 title='Delete extra home info'
25 />
26 </View>
27 );
28};

돌아가기

컬렉션

이 페이지의 내용