Brief Intro to Value Objects of Foundation Framework

本文介绍了Foundation框架中的关键价值对象类,如NSValue、NSNumber、NSDecimalNumber等,这些类为基本数据类型提供了面向对象的封装,并支持日期时间操作、缓存管理等功能。

Value Objects

The Foundation Framework value object classes implement object-oriented wrappers for primitive data types, along with general-purpose system information, tools, and locale support. The NSCalendarNSDateNSCalendarDate,NSDateComponents, and NSTimeZone classes provide support for date and time programming and formatting. The NSValueNSNumberNSDecimalNumber, andNSDecimalNumberHandler classes provide object-oriented wrappers for primitive data types, which can then be manipulated and/or added to collection objects. TheNSDataNSMutableData, and NSPurgeableData classes provide object-oriented wrappers for byte buffers. NSValueTransformer is used to transform values from one representation to another. NSNull is a singleton object used to represent null values in collection objects that don’t allow nil values. NSLocale provides support for locales, a collection of information used to adapt software for a specific region or language. NSCache provides an in-memory system cache for the temporary storage of objects that are expensive to re-create.

NSValue

The NSValue class is a container for a single data item. It can hold both C and Objective-C data types (including primitives) of constant length and is typically used to allow an item to be stored in a collection object (NSArrayNSSet, etc.), because these require their elements to be objects. The code fragment in Listing 10-3 creates an NSValue instance from a value of type int.

Listing 10-3.  Creating an NSValue Instance

int ten = 10;
int *tenPtr = &ten;
NSValue *myInt = [NSValue value:&tenPtr withObjCType:@encode(int *)];

Note that the type is specified using an @encode directive. This value can now be stored in a collection object. The following statement retrieves the int value of theNSValue object and assigns this value to the variable result.

int result = *(int *)[myInt pointerValue];

NSNumber

The NSNumber class is a subclass of NSValue that functions as a container for primitive (scalar) types. It defines a set of methods for creating and accessing number objects as primitive types: signed/unsigned charintshort intlong intlong long intNSIntegerfloatdouble, or BOOL types. NSNumberincludes numerous class factory methods (whose names all begin withnumberWith...) for creating and initializing an NSNumber with an input parameter of the specified primitive type. The following statement uses thenumberWithDouble: method to create an NSNumber instance of type double and assign it to a variable named degrees2Radians.

NSNumber *degrees2Radians = [NSNumber numberWithDouble:(3.1415/180.0)];

NSNumber also includes initialization methods (whose names all begin withinitWith...) to initialize an allocated NSNumber object with the input parameter value. The corresponding NSNumber ...Value methods (one for each of the supported types) can be used to retrieve a primitive value from an NSNumberobject, for example:

double d2r = [degrees2Radians doubleValue];

NSNumber also includes a stringValue method to get the string representation of an NSNumber instance.

NSDecimalNumber

NSDecimalNumber is a subclass of NSNumber that is used to perform decimal arithmetic. It includes methods for creating and initializing decimal numbers, and methods for performing standard arithmetic operations (addition, subtraction, multiplication, division, etc.). It is especially useful for performing these operations on numbers where rounding errors can be significant (for example, with currency).Listing 10-4 adds two NSDecimalNumber objects and assigns the result to anNSDecimalNumber object named sum.

Listing 10-4.  Adding Two Numbers Using NSDecimalNumber

NSDecimalNumber *num1 = [NSDecimalNumber decimalNumberWithString:@"2.56"];
NSDecimalNumber *num2 = [NSDecimalNumber decimalNumberWithString:@"7.78"];
NSDecimalNumber *sum = [num1 decimalNumberByAdding:num2];

The NSDecimalNumber methods that perform arithmetic operations include parameters that can be used to specify how calculation errors and rounding are handled.

NSNumber Literals

Objective-C provides language-level support for creating NSNumber literals. Any character, numeric, or Boolean literal that is prefixed with an @ character evaluates to an NSNumber object initialized to that value. The following statements are equivalent:

NSNumber *num = [NSNumber numberWithInt:17];
NSNumber *num = @17;

NSNumber literals are created from scalar values, not expressions. In addition,NSNumber literals are evaluated at runtimethey are not compile-time constants and thus cannot be used to initialize static variables. In essence, the literal @17 is actually shorthand for the expression [NSNumber numberWithInt:17], an object message that is evaluated at runtime. More information on NSNumber literals is provided in Chapter 16, which explores Objective-C literals in depth.

Date and Time Support

The NSCalendarNSDateNSCalendarDateNSDateComponents, and NSTimeZoneclasses provide support for date and time programming and formatting. An NSDateinstance represents an absolute timestamp. The following statement creates a date that represents the current time.

NSDate *now = [[NSDate alloc] init];

The following statements compare two dates and return an NSComparisonResultthat indicates whether the input date is later, the same, or earlier than the receiver’s dates.

NSTimeInterval secondsPerDay = 24 * 60 * 60;
NSDate *tomorrow = [now dateByAddingTimeInterval:secondsPerDay];
NSComparisonResult *result = [now compare:tomorrow];

The NSCalendar class encapsulates calendar information used to organize periods of time. It provides an implementation for several different calendars, including the Buddhist, Gregorian, Hebrew, Islamic, and Japanese calendars. The following statement returns a calendar for the current user’s chosen locale.

NSCalendar *currentCalendar = [NSCalendar currentCalendar];

The following statement creates a Gregorian calendar.

NSCalendar *gregorianCalendar = [[NSCalendar alloc]
                                initWithCalendarIdentifier:NSGregorianCalendar];

NSCalendar provides methods for retrieving the component elements of a date in a calendar, represented as NSDateComponents objects.

The NSDateComponents class represents the component elements of a date/time. It is used to set/get these elements, and also specify a time interval. The following statements retrieve date components from a current calendar object with monthly calendar units.

NSDate *date = [NSDate date];
NSDateComponents *components = [currentCalendar components:NSMonthCalendarUnit
                                                    fromDate:date];

NSCache

In computer programming, a cache is a mechanism that stores data so that future requests for the same data can be retrieved more quickly. They are commonly used to store objects that are expensive to re-create. The Foundation FrameworkNSCache class provides an in-memory system cache for the temporary storage of objects that are expensive to re-create. In addition to managing cache values, the class includes methods for managing the cache size, managing discarded objects, and managing the cache delegate. A cache delegate conforms to theNSCacheDelegate protocol, and is sent messages when an object is about to be evicted or removed from the cache. An NSCache instance stores key-value pairs, similar to an NSDictionary (to be discussed later in this chapter). It differs in that it provides autoremoval policies, and thus manages memory utilization. The following code fragment creates an NSCache instance, sets the number of objects the cache can hold, and then adds an object to the cache.

NSCache *cache = [[NSCache alloc] init];
[cache setCountLimit:500];
[cache setObject:@"Hello, World!" forKey:@"greeting"];
代码下载地址: https://pan.quark.cn/s/a4b39357ea24 在当代Web开发领域中,前后端分离的架构模式已广泛普及,这种模式有助于提升开发效能,清晰界定工作职责,并支持前后端独立地进行开发与部署工作。当前项目借助Spring Boot框架构建了后端服务接口,并搭配Vue.js技术完成前端界面呈现,同时运用axios工具应对跨域通信挑战,从而形成一个完整的前后端分离实践范例。 1. **Spring Boot**: Spring Boot可视为Spring框架的一个精简版本,其旨在简化Spring应用的初始构建及开发流程。在Spring Boot环境下,开发者能够迅速构建出具备生产环境要求水准的Spring应用程序。该框架整合了众多常用第三方库的配置选项,例如数据库连接管理、模板引擎应用、安全机制设定等,显著降低了标准配置的复杂程度。 2. **后端接口开发**: 在`springBoot实现后端接口.zip`文件中,主要包含了基于Spring Boot的后端服务功能实现。通常情况下,我们会设计RESTful风格的API,通过HTTP协议的CRUD操作(即创建、读取、更新、删除)来响应前端发起的请求。这些接口多采用Spring MVC的注解方式,如`@GetMapping`, `@PostMapping`, `@PutMapping`, `@DeleteMapping`等来定义,并借助Spring Data JPA或MyBatis等数据持久化框架与数据库进行数据交互。 3. **Vue.js**: Vue.js是一款轻量级的前端JavaScript框架,专注于用户界面的开发。它具备响应式的数据绑定机制和组件化的架构设计,使得开发者能够高...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值