ios developer tiny share-20160829

今天开始讲新的一章,关于Objective-C的封装数据,上一章我们讲了封装方法。

Encapsulating Data

In addition to the messaging behavior covered in the previous chapter, an object also encapsulates data through its properties.

This chapter describes the Objective-C syntax used to declare properties for an object and explains how those properties are implemented by default through synthesis of accessor methods and instance variables. If a property is backed by an instance variable, that variable must be set correctly in any initialization methods.

If an object needs to maintain a link to another object through a property, it’s important to consider the nature of the relationship between the two objects. Although memory management for Objective-C objects is mostly handled for you through Automatic Reference Counting (ARC), it’s important to know how to avoid problems like strong reference cycles, which lead to memory leaks. This chapter explains the lifecycle of an object, and describes how to think in terms of managing your graph of objects through relationships.

Properties Encapsulate an Object’s Values

Most objects need to keep track of information in order to perform their tasks. Some objects are designed to model one or more values, such as a Cocoa NSNumber class to hold a numeric value or a custom XYZPerson class to model a person with a first and last name. Some objects are more general in scope, perhaps handling the interaction between a user interface and the information it displays, but even these objects need to keep track of user interface elements or the related model objects.

Declare Public Properties for Exposed Data
Objective-C properties offer a way to define the information that a class is intended to encapsulate. As you saw in Properties Control Access to an Object’s Values, property declarations are included in the interface for a class, like this:

@interface XYZPerson : NSObject
@property NSString *firstName;
@property NSString *lastName;
@end

In this example, the XYZPerson class declares string properties to hold a person’s first and last name.

Given that one of the primary principles in object-oriented programming is that an object should hide its internal workings behind its public interface, it’s important to access an object’s properties using behavior exposed by the object rather than trying to gain access to the internal values directly.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值