开发者

Persistence in iOS: Property List Serialization vs. NSUserDefaults vs. Core Data

开发者 https://www.devze.com 2023-04-12 21:59 出处:网络
I\'m new to iOS. My requirement is to collect several error strings from inside the app and periodically post them to my web service. Each error is a simple NSString ~100 characters long. I may accumu

I'm new to iOS. My requirement is to collect several error strings from inside the app and periodically post them to my web service. Each error is a simple NSString ~100 characters long. I may accumulate upto 1000 error records between posts. The actual post will be done on a background thread, but the collection and persistence of the error logs will be done on the main thread. I'm trying to decide between one of the following methods for persistence:

1) Property list serialization (my log records would be NSArray of NSStrings)

2) N开发者_运维问答SUserDefaults (my NSArray would be the value object for some key in NSUserDefaults)

3) Core Data (But just one NSManagedObject for the log and only one property inside of it, the log message string)

Note that I say "logs" but I'm doing all the logging work manually. (Is there any other option?)

One important factor for me is to incrementally persist the log records on disk. In other words, if I have already persisted 500 log records, and 501st comes along, I do not want to re-persist 500+1 log records for efficiency reasons. It appears that using option (1) and (2) I cannot incrementally persist stuff. I think I'll have to rewrite the blob everytime. I'm still studying option (3). Just thought of getting an expert opinion on this :)


* Update * No need for Core Data or anything like that.

Just create a text file in your Documents directory call log.txt (anything is fine really). When you are ready to persist your NSArray, use the following method:

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

Whenever you are ready you can post the file, clear its contents, and you are ready for the next array.


I would use Core Data just because it makes everything so easy.

On the other hand, you don't really have to use either of them. If I am reading your question correctly you are already persisting the logs in your log files.

You can store a lastPost date in NSUserDefaults, find your log files that were created after the lastPost date, post the log files, update the lastPost date and be done.

On an unrelated note, sending logs like that could violate app guidelines depending on what you are sending and how clear it is to the user.


You might also use NSJSONSerialization which can write your array in JSON document format to a file, which is often useful if you want to send the data to a server later. Rules for property list and JSON are quite similar but not identical.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号