-1

I am trying to understand some code and I am wondering what this code does on OS X Application:

[[NSUserDefaults standardUserDefaults] retain]

It's set up as a variable. I am wondering if it gathers information about the system. I am trying to run an application inside virtual machine, but it won't let me and I am trying to analyse the code to see why, but I don't know Objective-C.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • It is nonsensical as far as I can tell. standardUserDefaults is a singleton, and therefore wouldn't be retained even in the strange circumstance of assigning it somewhere. – danh Nov 27 '16 at 14:46
  • @danh Why is assigning it somewhere a strange circumstance? – Willeke Nov 27 '16 at 16:02
  • It can be accessed any place with `[NSUserDefaults standardUserDefaults]`. – danh Nov 27 '16 at 16:04
  • Practically the code does nothing at all except unnecessarily increasing the retain counter of the `standardUserDefaults` singleton. – vadian Nov 27 '16 at 17:35
  • @danh calling `[NSUserDefaults standardUserDefaults]` once and storing the result in a variable runs faster. This isn't strange, it's efficient if you want to get or set a lot of preferences. – Willeke Nov 28 '16 at 00:34

1 Answers1

0

So before ARC (Automatic Reference Counting) was a thing, you would see retain and release everywhere.

When you allocate an object, you had to retain it, to increment the retain count. And if you ever called release, you would decrement the retain count. If the retain count ever hit 0, the object was released, -dealloc would be called

Now with ARC, the retain and release instructions are compiled in, based off of attributes of your object (strong, weak) you can read more about that here: Objective-C ARC: strong vs retain and weak vs assign

Anyways point being that your line there, as danh said, does nothing. Because [NSUserDefaults standardUserDefaults] is a singleton, there is no point in incrementing the retain count, because there's no threat of it being released from under you.
Although I don't think it is the weirdest thing to assign the standardUserDefaults to a local pointer, it would be just as effective to access the singleton every time you needed the standard defaults

Community
  • 1
  • 1
A O
  • 5,516
  • 3
  • 33
  • 68
  • 1
    No, calling `[NSUserDefaults standardUserDefaults]` every time isn't just as effective. Calling a method isn't effective. – Willeke Nov 28 '16 at 00:54