Storing an NSURL as a string in Core Data

99封情书 提交于 2019-12-05 08:51:24

Depending on Monogenerator or not, I will use the second approach. Override "getters" and "setters", perform the mapping from the URL to the string with

NSString *urlString = [url absoluteString];

and use setPrimitiveValue:forKey: and its counterpart like

- (void)setYourURL:(NSURL*)newURL {
    [self willChangeValueForKey:@"yourURL"]; // call to notify the world you are modifying that property
    NSString* yourURLAsString = // perform the conversion here...
    [self setPrimitiveValue:yourURLAsString forKey:@"yourURL"];
    [self didChangeValueForKey:@"yourURL"]; // call to notify the world you've modified that property
}

If your URL has spaces, you may also think to replace them with stringByReplacingPercentEscapesUsingEncoding:.

The answer depends somewhat on the URL actually is.

For file URLs

Use NSURL's routines for generating bookmark data and store that instead. This makes you resilient to files moving around, and can include security-scoping for sandboxed apps.

For everything else

Your options are to store:

  • String representation from -absoluteString
  • Data representation from CFURLGetBytes()
  • Data as produced by using an NSCoder

The last is probably only useful if you have URLs comprised of a -baseURL and wish to persist that knowledge.

In Xcode 9 and iOS 11+ you can simply use new URI type for storing URL.

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