binpress

Learn Objective-C: Data Encapsulation

Encapsulation is an important concept in object-oriented programming. By using class methods to access data stored in object properties, we can separate how that data is returned from how it is stored internally.

This is important because the structure of the data and how it is formatted can and will change over time. By encapsulating the data using class methods, we protect ourselves from change by making sure the data returned is always consistent. If we access the object properties directly, we would need to go through our code and make changes every time the structure or format of the data changes.

In Objective-C, we use properties, and the accessor methods in particular, help to hide the instance variables themselves. By indirectly accessing them, you get to control their access. You can also force the issue by making them readonly, which means only the containing class can use them. By using methods, you also don’t have to worry about how the instance variables themselves are set up; you simply access the methods that are provided, and have confidence the data returned will always be returned the same way, regardless how it is stored or structured.

This post is part of the Learn Objective-C in 24 Days course.

Author: Feifan Zhou

Scroll to Top