I hear the term "Class Wrapper" float around a lot, and I was curious what it is. I read explanations on this site about them, and they basically you just sound like a Singleton and Objective-C. My two questions are: 1. What is the difference between a singleton in the class wrapper? 2. Are class wrappers ever used in iOS projects, or do we use singletons in the iOS world more often?
What is the difference between a class wrapper and Java, and a singleton in Objective-C?
1.8k views Asked by Henry F AtThere are 2 answers
Singletons and class wrappers are two different concepts. A singleton refers to a class whose only role is to have one instance, hence the name. Say you wanted to build an address book and store multiple contacts within, it would make sense that there only be one address book instance in your application instead of creating multiple address books if the purpose of your application is only to keep track of contacts within a single address book.
Within Obj-C class wrappers form the concept of bridging a primitive data type inherited from the C language and having object representations for them. You gave the example of a float data type. In the case of numbers the foundation framework provides the abstract NSNumber class to 'wrap' around a primitive data type such as a float, or int and give you an object representation. From there you are able to store them in an array, or dictionary or deal with them as normal objects (send messages, extend, etc). Another great example of a generic class wrapper is the NSValue class that allows you to create object representations for say a CGPoint or CGRect, which are used extensively in iOS.
I think you are confused on what one of those entities is, they are not similar in the slightest (apart from being a part of software engineering...).
A singleton is a single object (of any class you like) that can be accessed from anywhere in the entire project by any bit of code you like. It's a single point in space that is reference-able from any other point in space.
A "Wrapper Class" is a class that wraps another class (or primitive). Say you want to pass an int to a function or method, that method modifies that int and you want the calling object to see the change. Since ints are passed by value instead of by reference (by default) any changes you make to that int in the called function are ignored by the caller. So the caller sees no change in the int's value. Now if you make an
Integer
object and make it wrap an int you can now pass thatInteger
object by reference to functions or methods, modify theInteger
object and get the modified value back into the calling function. AWrapper Class
wraps an object (or primitive) into another object to give it different functionality.