teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

解決できました。

2021/04/06 12:14

投稿

退会済みユーザー
title CHANGED
File without changes
body CHANGED
@@ -1,248 +1,4 @@
1
1
  以下のモデルのリストにデータを追加したいのですが、できませんでした。
2
2
  **handleUploadTweet**関数で、Userのtweetsに追加したいのですが、Tweetクラスだけに保存されてしまい、Userクラスには保存されていないことに気付きました。
3
3
  インスタンスを作り、そのインスタンスのプロパティに追加した後、まとめてList型のプロパティに保存するしようとしたのですができません。
4
- なぜ保存されないのか理解できる方、どうかご教授お願いします。
4
+ なぜ保存されないのか理解できる方、どうかご教授お願いします。
5
-
6
- ### User
7
- ```ここに言語を入力
8
- class User: Object {
9
- @objc dynamic var id: Int = 0
10
- @objc dynamic var username: String = ""
11
- @objc dynamic var profileImage: Data? = nil
12
- var tweets = List<Tweet>()
13
- override static func primaryKey() -> String? {
14
- return "id"
15
- }
16
- }
17
-
18
- class Tweet: Object {
19
- @objc dynamic var tweetId: Int = 0
20
- @objc dynamic var caption: String = ""
21
- let users = LinkingObjects(fromType: User.self, property: "tweets")
22
- var replyTweet = List<ReplyTweet>()
23
- override static func primaryKey() -> String? {
24
- return "tweetId"
25
- }
26
- }
27
- ```
28
-
29
- ### データを追加するクラス
30
- ```ここに言語を入力
31
- import Foundation
32
- import UIKit
33
- import RealmSwift
34
-
35
- protocol CreateNewIDRepository {
36
- func newId<T: Object>(model: T) -> Int?
37
- func replyNewId<T: Object>(model: T) -> Int?
38
- }
39
-
40
- enum UploadTweetConfiguration {
41
- case tweet
42
- case reply(Tweet)
43
- }
44
-
45
- class UploadTweetController: UIViewController {
46
- private let currentUser = CurrentUser.shared
47
- private let reuseIdentifier = "UploadTweetCell"
48
- private let realm = try! Realm()
49
- private var user: Results<User>!
50
- private var tweets: [Tweet] = [Tweet]()
51
- private let config: UploadTweetConfiguration
52
- private let actionButtonTitle: String
53
- private let placeholderText: String
54
- private let shouldShowReplyLabel: Bool
55
- private var replyText: String?
56
- var textViewHeight: NSLayoutConstraint!
57
- private let imagePicker = UIImagePickerController()
58
- private var selectedImage = [UIImage]()
59
- private var collectionView: UICollectionView!
60
-
61
- private lazy var actionButton: UIButton = {
62
- let button = UIButton(type: .system)
63
- button.addTarget(self, action: #selector(handleUploadTweet), for: .touchUpInside)
64
- return button
65
- }()
66
-
67
- private let cameraButton = UIBarButtonItem(barButtonSystemItem: .camera, target: self, action: #selector(cameraButtonTapped))
68
-
69
- private let profileImageView: UIImageView = {
70
- let iv = UIImageView()
71
- return iv
72
- }()
73
-
74
- private let captionTextView = UITextView()
75
-
76
- private let placeholderLabel: UILabel = {
77
- let label = UILabel()
78
- return label
79
- }()
80
-
81
- private var documentDirectoryFileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
82
-
83
- private let filePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
84
-
85
- init(user: Results<User>!, config: UploadTweetConfiguration){
86
- self.user = user
87
- self.config = config
88
- switch config {
89
- case .tweet:
90
- actionButtonTitle = "Tweet"
91
- placeholderText = "What?"
92
- shouldShowReplyLabel = false
93
- case .reply(let tweet):
94
- actionButtonTitle = "reply"
95
- placeholderText = "Reply!"
96
- shouldShowReplyLabel = true
97
- }
98
- super.init(nibName: nil, bundle: nil)
99
- }
100
-
101
- required init?(coder: NSCoder) {
102
- fatalError("init(coder:) has not been implemented")
103
- }
104
-
105
- override func viewDidLoad() {
106
- super.viewDidLoad()
107
- captionTextView.delegate = self
108
- collectionView = UICollectionView(frame: view.frame, collectionViewLayout: UICollectionViewFlowLayout())
109
- collectionView.reloadData()
110
- configureUI()
111
- commonInit(button: true)
112
- configureImagePicker()
113
- NotificationCenter.default.addObserver(self,
114
- selector: #selector(textViewDidChange(notification:)),
115
- name: UITextView.textDidChangeNotification, object: captionTextView)
116
- }
117
-
118
- override func viewDidAppear(_ animated: Bool) {
119
- super.viewDidAppear(animated)
120
- collectionView.reloadData()
121
- }
122
-
123
- deinit {
124
- NotificationCenter.default.removeObserver(self)
125
- }
126
-
127
- @objc private func handleTextInputChange(){
128
- }
129
-
130
- @objc private func handleCancel(){
131
- dismiss(animated: true, completion: nil)
132
- }
133
-
134
- @objc private func handleUploadTweet(){
135
- view.endEditing(true)
136
- let userRealm = User()
137
- let tweetRealm = Tweet()
138
- let replyTweetRealm = ReplyTweet()
139
- guard let caption = captionTextView.text else { return }
140
- uploadTweet(caption: caption, type: config) { [self] in
141
- switch config {
142
- case .tweet: // ここ
143
- tweetRealm.caption = caption
144
- tweetRealm.tweetId = newId(model: tweetRealm)!
145
- userRealm.tweets.append(tweetRealm)
146
- try! realm.write {
147
- realm.add(tweetRealm, update: .all)
148
- realm.add(userRealm.tweets)
149
- }
150
- case .reply(let tweet):
151
- replyTweetRealm.replyCaption = caption
152
- replyTweetRealm.replyTweetId = replyNewId(model: replyTweetRealm)!
153
- try! realm.write {
154
- tweet.replyTweet.append(replyTweetRealm)
155
- }
156
- }
157
- }
158
- dismiss(animated: true, completion: nil)
159
- }
160
-
161
- @objc private func textViewDidChange(notification: NSNotification){
162
- }
163
-
164
- @objc private func cameraButtonTapped(){
165
- }
166
-
167
- // MARK: - UI
168
-
169
- private func configureUI(){
170
- }
171
-
172
- private func configureNavigationBar(){
173
- }
174
-
175
- private func uploadTweet(caption: String, type: UploadTweetConfiguration, completion: @escaping() -> Void){
176
- completion()
177
- }
178
-
179
- private func configureImagePicker(){
180
- imagePicker.delegate = self
181
- imagePicker.allowsEditing = true
182
- }
183
-
184
- private func getDocumentsURL() -> NSURL {
185
- let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as NSURL
186
- return documentsURL
187
- }
188
-
189
- private func fileInDocumentsDirectory(filename: String) -> String {
190
- let fileURL = getDocumentsURL().appendingPathComponent(filename)
191
- return fileURL!.path
192
- }
193
-
194
- private func saveImageToDocuments(image: UIImage, path: String) {
195
- do {
196
- let pngImageData = image.pngData()
197
- try pngImageData!.write(to: URL(fileURLWithPath: path), options: .atomic)
198
- } catch {
199
- print(error)
200
- }
201
- }
202
-
203
- func saveImage() {
204
- }
205
-
206
- func imageNewId<T: Object>(model: T) -> Int? {
207
- }
208
-
209
- }
210
-
211
- extension UploadTweetController: CreateNewIDRepository {
212
-
213
- internal func newId<T: Object>(model: T) -> Int? {
214
- guard let key = T.primaryKey() else { return nil }
215
- if let last = realm.objects(T.self).sorted(byKeyPath: "tweetId", ascending: true).last,
216
- let lastId = last[key] as? Int {
217
- return lastId + 1
218
- } else {
219
- return 0
220
- }
221
- }
222
-
223
- internal func replyNewId<T: Object>(model: T) -> Int? {
224
- guard let key = T.primaryKey() else { return nil }
225
- if let last = realm.objects(T.self).sorted(byKeyPath: "replyTweetId", ascending: true).last,
226
- let lastId = last[key] as? Int {
227
- return lastId + 1
228
- } else {
229
- return 0
230
- }
231
- }
232
-
233
- }
234
-
235
- extension UploadTweetController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
236
- func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
237
- guard let image = info[.editedImage] as? UIImage else { return }
238
- selectedImage.append(image)
239
- collectionView.reloadData()
240
- dismiss(animated: true, completion: nil)
241
- }
242
- }
243
-
244
- extension UploadTweetController: UITextViewDelegate {
245
- func textViewDidChange(_ textView: UITextView) {
246
- }
247
- }
248
- ```