What does self refer to?
self
is the object that's executing the code that refers to self
. The scrollview
instance variable defined in your code snippet is part of some class; in this case it's surely a view controller. The difference between an object and a class is like the difference between a peach pie and a recipe for peach pie: the recipe is a specification that tells you all about peach pies, but you can't eat the recipe, whereas an actual peach pie is a distinct thing, and you can make several similar pies from a single recipe. Anyway, self
is the name of the specific object that's executing the didSet
method associated with the scrollview
variable.
Is it necessary to set scrollview.delegate as self? Why or why not?
A UIScrollView
object has a delegate
property the you can set to any object that knows how to be a scroll view's delegate, i.e. any object that implements the UIScrollViewDelegate
protocol. But since views are almost always managed by a view controller of some sort, it's pretty typical to have the view controller that manages the scroll view also act as it's delegate. The scroll view will work just fine with no delegate at all; setting up a delegate is only important if you want to do something in response to changes in the scroll view, or otherwise modify its behavior somehow. So, if a scroll view has a delegate, it's typically the view controller that manages that scroll view, and since it's probably also the view controller that sets up the scroll view in the first place self
(meaning the view controller) is what you'll see most of the time.