How should I store a large string, like a user agreement? [closed]

三世轮回 提交于 2020-01-05 07:27:50

问题


I can use a string literal like @"content", but I think it’s a waste of memory. Is there a custom solution for this situation?

I'm a new Xcoder, so may be this is not a good question, but I'm very confuse about the use of NSString...


回答1:


Put the text in a file. Let's say you name the file userAgreement.txt. Make sure the file is part of your target (check the Target Membership section of the File Inspector while you have the file open in the primary editor).

Read the contents of the file at runtime like this:

NSString *path = [[NSBundle mainBundle] pathForResource:@"userAgreement" ofType:@"txt"];
NSString *userAgreement = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];

A feature of this approach is that you can localize the file, and this code will automatically pick up the appropriate version for the user's locale.

Note that if you want to use a custom end-user license agreement (EULA), and you want to put this app in the App Store, you must enter the EULA in your app configuration in iTunes Connect.




回答2:


I'm not saying the other answers are wrong, and it's probably what I would do myself (loading the EULA from a file). But I wanted to clarify that, whether you keep it in a file or in a string literal, it will use the same amount of memory, as long as you're managing your memory and creating your object graph in a reasonable way.

If you're concerned about memory usage, you can still make it a string literal; just define it in its own 'myEula' class as a property, put the string literal class in your -init method, and if you're using manual reference counting make sure it gets released.

Then, when you need to show the user the agreement, create a new instance of the myEula class, access the appropriate property, and then release it, or remove references and let it get garbage collected.

You could also define it in the view controller you were using to display the EULA, which you probably will only be keeping in memory for a short time. Purists will tell you that this violates model-view-controller, but if the text is immutable I don't think it's a big deal.

The only way it would waste memory would be if it was defined as a string literal in an object that stays in memory permanently, like your app delegate, or if you were keeping all of your views in memory all the time--but that would likely mean that you have bigger problems than this one string literal.



来源:https://stackoverflow.com/questions/12967055/how-should-i-store-a-large-string-like-a-user-agreement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!