Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing an NSURL as a string in Core Data

I'm beginning to play around with Core Data and just have a question around storing something like a URL.

I've currently got it configured as a transformable which is working fine however I feel that it's probably storing excess data unnecessarily and since it can be easily represented with text I'm wondering whether I should just be storing the absolute URL as a string and instantiating an NSURL object when it's loaded (I suspect this is the case) and if so how should this be implemented?

My research so far leads me to think maybe use mogenerator and then just override the property accessors to deal with the conversion between the string and NSURL. Would just like to get a sense of how this or normally done or whether I am just making things difficult for myself by even bothering.

Cheers Nick

like image 585
Nick Dancer Avatar asked Feb 16 '13 08:02

Nick Dancer


3 Answers

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.

like image 55
Mike Abdullah Avatar answered Nov 07 '22 11:11

Mike Abdullah


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:.

like image 4
Lorenzo B Avatar answered Nov 07 '22 10:11

Lorenzo B


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

like image 4
Shmidt Avatar answered Nov 07 '22 09:11

Shmidt